Skip to content

Commit

Permalink
Resolve interval handling when startAt set in the past
Browse files Browse the repository at this point in the history
  • Loading branch information
buzzinJohnnyBoi committed May 11, 2024
1 parent 7fb70f1 commit a15ee0a
Show file tree
Hide file tree
Showing 2 changed files with 34 additions and 1 deletion.
14 changes: 13 additions & 1 deletion src/croner.js
Original file line number Diff line number Diff line change
Expand Up @@ -496,7 +496,19 @@ Cron.prototype._checkTrigger = function (target) {
* @returns {CronDate | null} - Next run time
*/
Cron.prototype._next = function (prev) {
const hasPreviousRun = (prev || this._states.currentRun) ? true : false;
let hasPreviousRun = (prev || this._states.currentRun) ? true : false;

// If no previous run, and startAt and interval is set, calculate when the last run should have been
if (!prev && this.options.startAt && this.options.interval) {
prev = this.options.startAt;
const now = new CronDate(undefined, this.options.timezone || this.options.utcOffset);
let prevTimePlusInterval = prev.getTime() + this.options.interval * 1000;
while (prevTimePlusInterval <= now.getTime()) {
prev = new CronDate(prev, this.options.timezone || this.options.utcOffset).increment(this._states.pattern, this.options, true);
prevTimePlusInterval = prev.getTime() + this.options.interval * 1000;
}
hasPreviousRun = true;
}

// Ensure previous run is a CronDate
prev = new CronDate(prev, this.options.timezone || this.options.utcOffset);
Expand Down
21 changes: 21 additions & 0 deletions test/node/js/src/suites/options.cjs
Original file line number Diff line number Diff line change
Expand Up @@ -260,4 +260,25 @@ module.exports = function (Cron, test) {
assert.equal(nextRuns.length,5);
});

test("Valid interval starting in the past should give correct start date", function () {
const now = new Date();

const yesterday = new Date(now);
yesterday.setDate(now.getDate() - 1);
yesterday.setHours(19, 31, 2);

const sixDaysFromNow = new Date(now);
sixDaysFromNow.setDate(now.getDate() + 6);
sixDaysFromNow.setHours(19, 31, 2);

const nextRun = Cron("* * * * * *", { interval: 60 * 60 * 24 * 7, startAt: yesterday.toISOString() }).nextRun();

assert.equal(nextRun.getFullYear(), sixDaysFromNow.getFullYear());
assert.equal(nextRun.getMonth(), sixDaysFromNow.getMonth());
assert.equal(nextRun.getDate(), sixDaysFromNow.getDate());
assert.equal(nextRun.getHours(), sixDaysFromNow.getHours());
assert.equal(nextRun.getMinutes(), sixDaysFromNow.getMinutes());
assert.equal(nextRun.getSeconds(), sixDaysFromNow.getSeconds());
});

};

0 comments on commit a15ee0a

Please sign in to comment.