node.jsnode-cron

cron job in node js running multiple times


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.


Solution

  • You can call Job.stop() from onTick:

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