Node.js: Cron jobs

Automate tasks effectively in Node.js with cron jobs

👋 Welcome to the Stackhero documentation!

Stackhero delivers a ready-to-use Node.js cloud environment designed to help you move faster:

  • Deploy to production in seconds with a simple git push. No extra tooling or manual setup is required.
  • Bring your own domain and benefit from automatic HTTPS certificates, keeping your application secure without extra configuration.
  • Automatic backups, one-click updates, and predictable pricing help you focus on shipping features, and Stackhero manages the infrastructure for you.
  • Built on private, dedicated infrastructure for consistent performance and strong security.

Save time and reduce operational overhead: you can have your application running on Stackhero's Node.js cloud hosting in just a few minutes.

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-cron npm module is another available tool for cron tasks, this guide specifically focuses on the cron module and its implementation.

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
  )
);

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 * * *

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.