Node.js: Cron jobs
Automate tasks effectively in Node.js with cron jobs
👋 Welcome to the Stackhero documentation!
Stackhero provides a ready-to-use Node.js cloud solution designed to help you move faster:
- Deploy your application to production in seconds with a simple
git push. No additional tools or manual configuration required.- Use your own domain and benefit from automatic HTTPS certificate setup, ensuring your application is secure without any extra steps.
- Enjoy automatic backups, one-click updates, and clear, predictable pricing so you can focus on developing features while Stackhero manages the infrastructure.
- Experience optimal performance and enhanced security thanks to a private, dedicated VM.
Save time and simplify your operations: it only takes a few minutes to try out Stackhero's Node.js cloud hosting solution!
When developing Node.js applications, automating repetitive tasks such as sending scheduled emails, cleaning expired data, or performing regular maintenance can significantly enhance both efficiency and scalability. The cron module, available on npm (cron module on npm), provides a straightforward and effective method 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.