Skip to content

Commit

Permalink
inital commit
Browse files Browse the repository at this point in the history
  • Loading branch information
Mark Schmale committed Jan 3, 2011
0 parents commit 78839f4
Show file tree
Hide file tree
Showing 3 changed files with 104 additions and 0 deletions.
52 changes: 52 additions & 0 deletions Executor.js
Original file line number Diff line number Diff line change
@@ -0,0 +1,52 @@
var Events = require('events'),
sys = require('sys');
/**
* Author: Mark Schmale
*/
module.exports = Executor = function(func) {
Events.EventEmitter.call(this);
this.func = func;
this.queue = [];
this.running = 0;

this.on('job_queue_started', function() { this.running++; });

this.on('job_queue_ready', function() {
this.running--;
if(this.running <= 0) {
this.running = 0;
this.emit('all_queues_ready');
}
});

this.on('job_done', function() {
this.execute();
});
}
sys.inherits(Executor, Events.EventEmitter);

Executor.prototype.push = function(value) {
this.queue.unshift(value);
return this;
}

Executor.prototype.pop = function() {
return this.queue.pop();
}

Executor.prototype.startExecution = function(cnt) {
for(var i=0;i<cnt;i++) {
this.emit('job_queue_started');
this.execute();
}
}

Executor.prototype.execute = function() {
if(this.queue.length >= 1) {
var args = this.pop();
this.func.apply(this, args);
} else {
this.emit('job_queue_ready');
}
}

24 changes: 24 additions & 0 deletions README
Original file line number Diff line number Diff line change
@@ -0,0 +1,24 @@
===
API
===

var ex = new Executor(function(arg1, arg2) {
var self = this; // Tip: save your object reference!
// to what you have to do
// this is bind to the executor
do.async.stuff(function() {
self.emit('job_done'); // this starts the next job
});
}

ex.push([arg1, arg2]); // add new arguments for execution

ex.startExecution(x); // start x queues

======
Events
======

- all_queues_done: All running queues are done
- job_queue_done: A running queue is done (no more arguments left)
- job_done: you emit it, you should know it!
28 changes: 28 additions & 0 deletions test.js
Original file line number Diff line number Diff line change
@@ -0,0 +1,28 @@
var Executor = require('./Executor');

var f = function(val, timeout) {
var self = this;
console.log('waiting for ' + val + ' ');
setTimeout(function() {
console.log('GOT ' + val);
self.emit('job_done');
}, timeout);
}

var e = new Executor(f);
console.log(e.prototype);
e.push(['a', 200]);
e.push(['b', 1000]);
e.push(['c', 10]);
e.push(['d', 100]);
e.push(['e', 200]);
e.push(['f', 1000]);
e.push(['g', 10]);
e.push(['h', 100]);

e.on('all_queues_ready', function() { console.log('ALL_JOBS_DONE'); });
e.on('job_queue_ready', function() { console.log('JOB_QUEUE_DONE'); });
e.on('job_done', function() { console.log('JOB_DONE'); });

e.startExecution(4);

0 comments on commit 78839f4

Please sign in to comment.