In node-cron, how do I get the timing of the next cron-job? e.g. cronJob.nextCronJob().time, or other properties. There are no methods in the documentation to show this.
Asked
Active
Viewed 9,488 times
2 Answers
7
I'm not aware of any way of getting this using the node-cron module. You can do this with the cron module however, using the cronJob.nextDates() function, like so:
const CronJob = require("cron").CronJob;
const cronJob = new CronJob(
"*/30 * * * * *",
() => {
console.log("Timestamp: ", new Date());
},
null,
true
);
setInterval(() => {
console.log("Next job time:", cronJob.nextDates().toISOString());
}, 5000);
If you have to use the node-cron module, you could have a look at cron-parser, this will parse a cron expression and give you the next run time(s), e.g.
const parser = require('cron-parser');
const cronExpression = "*/30 * * * * *";
const interval = parser.parseExpression(cronExpression);
console.log('Next run:', interval.next().toISOString());

Terry Lennox
- 29,471
- 5
- 28
- 40
-
3Or simply `cronJob.nextDates().toISOString()`. With no argument `nextDates()` will return next run time. – Enslev Jun 25 '20 at 13:03
-
Oh, excellent @Enslev, thank you, that is certainly a nicer syntax. – Terry Lennox Jun 25 '20 at 13:36
-
1The problem with the "cron" module is that it is not as supported as "node-cron" for example, it only runs on Linux. – Solobea Jun 25 '20 at 14:53
-
Also, if I were to use the "cronJob.nextDates().toISOString()", is there a better way to get "how long" until next job instead of converting to number and minusing Date.now() or something else? – Solobea Jun 25 '20 at 14:54
-
I believe it should run on Windows too, it's worked for me on Windows 10 in any case. I don't know if this helps though!. The nextDates() call will return a moment object so you should be able to call .toDate().getTime() to get unix time. – Terry Lennox Jun 25 '20 at 14:59
0
below here is how we previously used to get ISOString however this won't work now since corn has upgraded its version. With its new version, they have dropped momentJs and are using luxon.
cronJob.nextDates(1)[0].toISOString()
In order to get it to work now, you can use the following code.
cronJob.nextDates(1)[0].toJSDate().toISOString()

Zee
- 1
- 1