Search code examples
node.jsprocesscronbackgroundworkercron-task

Does cron job block the main process or nodejs will create a worker to do cron task


I am using node-cron to do some heavy tasks (update database) every minute. Does this task use main process to work or nodejs will create some workers to do these taks?

var CronJob = require('cron').CronJob;
new CronJob('0 * * * * *', function() {
  //Update database every minute here
  console.log('Update database every minute');
}, null, true, 'America/Los_Angeles');

Solution

  • It is supposed to create a worker for you.. It is not well documented in the library docs but: 1) You can see at the dependencies, it depends on node-worker. 2) If the cron job were to be blocking, then the waiting for the cron job to execute (in this case, a minute) would be blocking as well. This is because the main thread will just wait until it has to do it. Which in this case, it will be no cron job because it will be a simple sleep() and then execute.

    Although, if you want to be sure, try doing a nodejs main program with a "while true" and inside probably writing something to console. And make a cronjob that every minute it will execute a sleep() command for the time you wish. The expected symptom is that the writing in console should never stop ..

    Hope this helps.. Cheers