Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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');
like image 502
Vo Thanh Thang Avatar asked May 20 '15 23:05

Vo Thanh Thang


People also ask

Does node-cron block?

First, node-cron has the same merits and demerits as Node. js, being a runtime of JavaScript, which happens to be a non-blocking single-threaded language that uses the event loop.

What is cron job Nodejs?

The cron command-line utility, also known as cron job, is a job scheduler on a Unix-like operating system. Users who set up and maintain software environments use cron to schedule jobs (commands or shell scripts) to run periodically at fixed times, dates, or intervals.

How does a cron job work?

cron is a Linux utility that schedules a command or script on your server to run automatically at a specified time and date. A cron job is the scheduled task itself. Cron jobs can be very useful to automate repetitive tasks.


Video Answer


2 Answers

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

like image 64
Cesar Villasana Avatar answered Sep 21 '22 15:09

Cesar Villasana


Any blocking operation will block the main thread indeed, at least with node-cron.

I have tried with an expressjs app where the cron job attemps to fetch data from web regularly:

// app.js
...

/* Routes */

app.use("/", valueRoutes);

/* Cron Job */

cron.schedule(CRON_EXP, refreshData); // long running asyn operation

export default app;

During the refreshData method execution, the express app is not able to respond to requests.

like image 44
Orkun Ozen Avatar answered Sep 25 '22 15:09

Orkun Ozen