From 249ef3e799a5d9cd65a1954c979bf8eaae8c3959 Mon Sep 17 00:00:00 2001 From: Kristijan Sedlak Date: Sun, 5 May 2019 10:38:40 +0200 Subject: [PATCH] Fix old recurring job processing --- package.json | 2 +- src/cron.ts | 4 +++- src/tests/cron.test.ts | 18 ++++++++++++++++++ 3 files changed, 22 insertions(+), 2 deletions(-) diff --git a/package.json b/package.json index 41c27c7..4f01240 100644 --- a/package.json +++ b/package.json @@ -1,6 +1,6 @@ { "name": "mongodb-cron", - "version": "1.6.0", + "version": "1.7.0", "description": "MongoDB collection as crontab", "main": "./dist/index.js", "types": "./dist/index.d.ts", diff --git a/src/cron.ts b/src/cron.ts index d1df4af..d109070 100644 --- a/src/cron.ts +++ b/src/cron.ts @@ -190,7 +190,9 @@ export class MongoCron { currentDate: future.toDate(), endDate: dot.pick(this.config.repeatUntilFieldPath, doc), }); - return interval.next().toDate(); + const next = interval.next().toDate(); + const now = moment().toDate(); + return next < now ? now : next; // process old recurring jobs only once } catch (err) { return null; } diff --git a/src/tests/cron.test.ts b/src/tests/cron.test.ts index 131feca..c20e95b 100644 --- a/src/tests/cron.test.ts +++ b/src/tests/cron.test.ts @@ -128,6 +128,24 @@ spec.test('recurring documents should be unlocked when prossed', async (ctx) => ctx.is(processed, 3); }); +spec.test('recurring documents should process from current date', async (ctx) => { + let processed = 0; + const past = moment().subtract(10, 'days'); + const collection = ctx.get('collection'); + const cron = new MongoCron({ + collection, + onDocument: () => processed++, + }); + await collection.insertOne({ + sleepUntil: past.toDate(), // should be treated as now() date + interval: '* * * * * *', + }); + await cron.start(); + await sleep(2000); + await cron.stop(); + ctx.true(processed <= 4); +}); + spec.test('condition should filter lockable documents', async (ctx) => { let count = 0; const collection = ctx.get('collection');