JN_newbie
JN_newbie

Reputation: 6102

cron job is not working node-cron

I am trying to run a cron job after 10 minutes, sometimes it runs after 10 minutes and sometimes it runs after like 2 minutes when I call the webservice. Below is the code

router.post('/getUser', function (req, res) {
    var task = cron.schedule('0 */10 * * * *', function () {
        console.log("cron job started")
     }, false);
     task.start();
})

It should always runs after 10 minutes not like sometime 2 minutes as soon as the webservice is called.

Upvotes: 0

Views: 10209

Answers (1)

Felix
Felix

Reputation: 5911

The cron syntax says to run the command at a fix time not after an interval.

The */10 means execute the command if the modulo is 0

In your case the code will be excecuted at second 0 of every 10 minutes at every hour at every day and so on.

So your cron will be executed for instance at 09:00, 09:10, 09:20, 09:30 and so on.

The only way I know with build in methods is to use something like

setTimeout(myFunc, 10 * 60 * 1000);

An other option is to set a fixed cron running at the calculated correct time now +10 minutes with moment.js where you specify the exact execution time.

Example

var moment = require('moment')


router.post('/getUser', function (req, res) {
var cronString = moment().second() +' '+ moment().add(10,'minutes').minute() +' '+ moment().hour() +' '+ moment().day() +' '+ moment().month() +' *';

var task = cron.schedule(cronString, function () {
    console.log("cron job started")
 }, false);
 task.start();
})

But beware of the fact that this would be executed every year at the same time ;)

Upvotes: 4

Related Questions