Monday, March 14, 2022

[SOLVED] How do you calculate past cron jobs schedules?

Issue

I would like to be able to find the times a cron job would have ran given the cron string. For example, with 0 */5 * * * *, the job runs every five minutes. If it is 13:02, the next job is at 13:05 and the last job was at 13:00. If there is a library out there that does this, I would like to use that if possible.


Solution

I'd consider using cron-parser, this allows you to determine previous and future cron times from a cron expression.

For example:

const parser = require('cron-parser');

const options = {
  currentDate: new Date('2020-06-25T13:02:00Z'),
  iterator: true
};

const interval = parser.parseExpression('0 */5 * * * *', options);

console.log("Previous run:", interval.prev().value.toISOString());
console.log("Next run:", interval.next().value.toISOString());

You should see something like:

 Previous run: 2020-06-25T13:00:00.000Z
 Next run: 2020-06-25T13:05:00.000Z


Answered By - Terry Lennox
Answer Checked By - David Goodson (WPSolving Volunteer)