cron job in node js running multiple times

4.6k views Asked by At

I am running a cron job using the module node-cron for node js . My code is below.

var Job = new CronJob({

cronTime: '* * 01 * * *', //Execute at 1 am every day

onTick  : function() {

    co(function*() {

        yield insertToDatabase(); //this is the function that does insert operation

    }).catch(ex => {

        console.log('error')

    });

},
start   : false,

timeZone: 'Asia/Kolkata'
});

I need to execute this only one time but this cronjob once starts runs multiple times due to which same data gets inserted to my database. I only need to run this job only one time. What should i do.

3

There are 3 answers

3
robertklep On BEST ANSWER

You can call Job.stop() from onTick:

onTick : function() {
  Job.stop();
  co(function*() {
    yield insertToDatabase();
  }).catch(ex => {
    console.log('error');
  });
}
0
Sushil On

In my case, i changed my code from this :

var job = new CronJob('*/59 * * * *', onTick, onComplete, true, 'Asia/Kolkata'); // onTick and onComplete is a function, which i'm not showing here
job.start();

To this :

var job = new CronJob('*/59 * * * *', onTick, onComplete, false, 'Asia/Kolkata'); // onTick and onComplete is a function, which i'm not showing here
job.start();

Thanks

0
devonrimmington On

I know I am late to the party but I think that I have a solution. I hope this can help someone else in the future (Hi future!)

I encountered what I think to be the same issue as the asker, that is, the OnTick function executes multiple times after the scheduled time, this appeared to the author to be an endless loop. The asker expected this function to run only once at the scheduled time everyday (today, tomorrow, etc).

With that in mind the cause of this "issue" is simple. The cron job is scheduled to to exactly this. The cron time entered is * * 01 * * * which means the hour is 01 (aka 1:00am) but the minutes and seconds are *. This means any minute and any second where the hour is 01. So this will run from 1:00am up until 1:59am. It will run for each second of each minute until 2:00am. If the author had waited until 2:00am the "looping" would have ceased.

The solution is to set the seconds and minutes to anything that is not * (0 in my case worked).

I feel really silly for not having figured this out right away but here it is!