Node.js: Cron jobs
Automate tasks effectively in Node.js with cron jobs
👋 Welcome to the Stackhero documentation!
Stackhero offers a ready-to-use Node.js cloud solution that provides a host of benefits, including:
- Deploy your application in seconds with a simple
git push.- Use your own domain name and benefit from the automatic configuration of HTTPS certificates for enhanced security.
- Enjoy peace of mind with automatic backups, one-click updates, and straightforward, transparent, and predictable pricing.
- Get optimal performance and robust security thanks to a private and dedicated VM.
Save time and simplify your life: it only takes 5 minutes to try Stackhero's Node.js cloud hosting solution!
When developing Node.js applications, automating repetitive tasks like sending scheduled emails, cleaning expired data, or performing regular maintenance can significantly improve both efficiency and scalability. The cron module, available on npm (cron module on npm), offers a straightforward and effective way to implement such automation.
Note: While the
node-cronnpm module is another available tool for cron tasks, this guide specifically focuses on thecronmodule and its implementation.
Getting started
To begin using the cron module in your project, include it as a dependency by executing the following command:
npm install cron
Once the module is installed, you can start scheduling and managing cron jobs in your application. Here is a practical example:
const cron = require('cron');
const cronJobs = [];
// Gracefully handle application shutdown by stopping all scheduled cron jobs.
// When deploying new code or shutting down the app, a termination signal (SIGTERM) is sent.
// This ensures the app stops all running cron jobs before exiting.
process.on('SIGTERM', () => {
cronJobs.forEach(cronJob => cronJob.stop());
});
// Schedule a cron job to execute every second.
cronJobs.push(
new cron.CronJob(
'* * * * * *', // Schedule: Every second
() => {
console.log("This message will appear every second.");
},
null,
true
)
);
// Schedule a cron job to execute every minute.
cronJobs.push(
new cron.CronJob(
'0 */1 * * * *', // Schedule: Every minute
() => {
console.log("This message will appear every minute.");
},
null,
true
)
);
Understanding cron syntax
The cron module uses the standard UNIX cron syntax for defining schedules. Here are a few common examples:
- Every second:
* * * * * * - Every 30 seconds:
*/30 * * * * * - Every 10 minutes:
0 */10 * * * * - Every 2 hours:
0 0 */2 * * *
Additional resources
You are now equipped to automate tasks using the cron module in your Node.js applications. For more detailed information and examples, visit the official cron module repository and check out the examples directory.