blob: ef86572de3be4bd18267835fd11e4f00e5217118 (
plain)
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
|
const cron = require('cron');
const Bluebird = require('bluebird');
const { model } = require('mongoose');
const schema = require('./event.schema.js');
const CronJob = cron.CronJob;
schema.methods.computeNextRunAt = function() {
const job = new CronJob(this.schedule);
const nextRunAt = job.nextDates();
return new Date(nextRunAt);
};
schema.pre('save', function(next) {
this.nextRunAt = this.computeNextRunAt();
next();
});
schema.statics.rescheduleOldEvents = async function () {
console.log('Reschedule old events');
const oldEvents = await this.find({
nextRunAt: {
// TODO: skip single-fire events
$lt: new Date()
},
});
// Saving events triggers computing new nextRunAt
return Bluebird.map(oldEvents, event => event.save());
};
schema.statics.findNextEvent = function () {
return this.findOne(
{
nextRunAt: {
$exists: 1,
$gt: new Date()
},
},
null,
{
sort: {
nextRunAt: 1
}
}
)
};
const Model = model('Event', schema);
module.exports = Model;
|