Running Scheduled Tasks In Node.js
Lots of web services need to run tasks at a particular time. This could be to perform a clean-up or maintenance operation, or simply to retrieve and process some data.
JavaScript has built in methods for running a task in a scheduled number of seconds. However, the syntax and architecture of these methods is a bit clumsy and there is no built in management to cancel jobs.
Fortunately in Node.js there are many libraries that perform just these tasks. One of these libraries is node-crontab which is available on GitHub or NPM.
The syntax of node-crontab is simple and straightforward, particularly if you have ever set up a scheduled task using cron on a linux system before. The time for the scheduled task is provided in cron format (either a specific time to run at, or a time interval); the task is provided as a function to run. There are some other optional parameters, such as the possibility of passing in arguments, changing what this points to, and stopping the task from running repeatedly.
The following code will print the message “I am running from cron” to the log every 15 minutes:
var cron = require('node-crontab');
var log_job = cron.scheduleJob("*/15 * * * *", function() {
console.log("I am running from cron");
});
To run a task at 0315 every morning, use the following code:
var early_morning = cron.scheduleJob("15 3 * * *", function() {
console.log("It's very early in the morning!");
});
To kill an existing job:
cron.cancelJob(log_job);
In summary, node-crontab is very simply to use and great for scheduling tasks in Node.js