summaryrefslogtreecommitdiff
path: root/src/services/events/event.model.js
diff options
context:
space:
mode:
authoreug-vs <eug-vs@keemail.me>2020-11-27 22:41:25 +0300
committereug-vs <eug-vs@keemail.me>2020-11-27 22:41:25 +0300
commit9f7115217c34732753102e044a94711400b5affc (patch)
tree364390decc2b093162ad740838c8add16d2955c7 /src/services/events/event.model.js
parent6a4e4402a52c6649f0ffb1c6a1e9183caaf6e313 (diff)
downloadbsu-fantom-9f7115217c34732753102e044a94711400b5affc.tar.gz
feat: use cron to schedule jobs
Diffstat (limited to 'src/services/events/event.model.js')
-rw-r--r--src/services/events/event.model.js55
1 files changed, 55 insertions, 0 deletions
diff --git a/src/services/events/event.model.js b/src/services/events/event.model.js
new file mode 100644
index 0000000..ef86572
--- /dev/null
+++ b/src/services/events/event.model.js
@@ -0,0 +1,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;
+
+
+