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');
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.
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.
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.
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
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.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With