Skip to content

Instantly share code, notes, and snippets.

@kylehotchkiss
Created January 21, 2013 22:48
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save kylehotchkiss/4590252 to your computer and use it in GitHub Desktop.
Save kylehotchkiss/4590252 to your computer and use it in GitHub Desktop.
HOW NOT TO WRITE A DAEMON/QUEUE SYSTEM
/**
*
* FNSTraj | Worker Process
* Copyright 2011-2012 Hotchkissmade
* Released under the GPL
*
*/
var http = require("http");
var fnstraj = require("./predictors/fnstraj.js");
var database = require("./library/database.js");
var COUNT = 0;
////////////////
// Queue Loop //
////////////////
var worker = function() {
setTimeout(function() {
COUNT++;
console.log("Worker Clock: " + COUNT + ".");
database.read('/queue/', function( results, error ) {
if ( typeof error !== "undefined" && error ) {
process.nextTick( worker );
} else {
var queue = results;
database.read('/flights/', function ( results, error ) {
if ( typeof error !== "undefined" && error ) {
process.nextTick( worker );
} else {
var flights = results;
if ( !flights.error && typeof queue.rows[0] !== "undefined" ) {
for ( flight in flights.rows ) {
if ( flights.rows[flight].doc._id === queue.rows[0].doc._id ) {
var thisFlight = flights.rows[flight].doc;
console.log("Flight " + thisFlight._id + " started");
thisFlight.duration = fnstraj.vertPred(thisFlight.launch.altitude, thisFlight.balloon.burst, thisFlight.balloon.radius, thisFlight.balloon.lift);
fnstraj.predict(thisFlight, function() {
database.remove('/queue/' + thisFlight._id);
console.log("Flight " + thisFlight._id + " completed");
process.nextTick( worker );
});
}
}
} else {
process.nextTick( worker );
}
}
});
}
});
}, 10000);
};
///////////////
// Run Queue //
///////////////
(function() {
worker();
})();
//////////////////
// Exit Cleanly //
//////////////////
/*process.on('exit', function() {
console.log('\nAbout to exit.');
});*/
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment