diff --git a/lib/agenda.js b/lib/agenda.js index 2d08d2751..c1204e93b 100644 --- a/lib/agenda.js +++ b/lib/agenda.js @@ -101,7 +101,11 @@ Agenda.prototype.schedule = function(when, name, data) { Agenda.prototype.saveJob = function(job, cb) { var fn = cb; - var props = getJobProperties(job); + + var props = job.toJSON(); + + delete props._id; + if(props.type == 'single') this._db.findAndModify({name: props.name, type: 'single'}, {}, {$set: props}, {upsert: true, new: true}, processDbResult); else { @@ -147,7 +151,9 @@ Agenda.prototype.stop = function() { function processJobs() { var definitions = this._definitions, self = this; + var now = new Date(); + this.jobs({nextRunAt: {$lte: now}}, {sort: {'priority': -1}}, function(err, jobs) { if(err) throw(err); else fillJobQueue(); @@ -178,12 +184,3 @@ function processJobs() { } }); } - -function getJobProperties(job) { - var props = {}; - for(var key in job.attrs) { - props[key] = job.attrs[key]; - } - delete props._id; - return props; -} diff --git a/lib/job.js b/lib/job.js index 529b078f6..824cb57a1 100644 --- a/lib/job.js +++ b/lib/job.js @@ -23,6 +23,21 @@ var Job = module.exports = function Job(args) { this.attrs = attrs; }; +Job.prototype.toJSON=function(){ // create a persistable Mongo object -RR + var self=this, + attrs=self.attrs||{}; + return { + _id: attrs._id, + name: attrs.name, + data: attrs.data, + priority: attrs.priority, + lastRunAt: attrs.lastRunAt ? new Date(attrs.lastRunAt) : null, + lastFinishedAt:attrs.lastFinishedAt ? new Date(attrs.lastFinishedAt) : null, + nextRunAt: attrs.nextRunAt ? new Date(attrs.nextRunAt) : null, + repeatInterval:attrs.repeatInterval, + type: attrs.type + }; +}; Job.prototype.computeNextRunAt = function() { var interval = this.attrs.repeatInterval;