Create and Manage Cron Jobs in Node.js

November, 18th 2024 2 min read

Cron jobs are essential for automating repetitive tasks like sending emails, cleaning databases, or generating reports. In Node.js, you can use libraries such as node-cron or agenda to automate tasks easily. This guide walks you through creating cron jobs with node-cron, explaining patterns, advanced usage, and best practices.

Step 1: Install the Required Package

We’ll use node-cron, a lightweight and widely used scheduler.

npm install node-cron

Step 2: Set Up Your Project

Initialize a new Node.js project:

mkdir cron-job-example
cd cron-job-example
npm init -y

Then install node-cron:

npm install node-cron

Step 3: Create Your First Cron Job

Create index.js and add:

js
const cron = require('node-cron');

// Run every minute
cron.schedule('* * * * *', () => {
  console.log('Cron job executed at', new Date().toLocaleString());
});

console.log('Cron job is running...');

Cron Syntax Explained

Cron patterns follow this structure:

lua
* * * * *
| | | | |
| | | | +--- Day of week (0-7)
| | | +----- Month (1-12)
| | +------- Day of month (1-31)
| +--------- Hour (0-23)
+----------- Minute (0-59)

Common examples:

  • 0 9 * * * — Run daily at 9:00 AM
  • */5 * * * * — Every 5 minutes
  • 0 0 * * 0 — Every Sunday at midnight

Step 4: Run the Cron Job

Run:

node index.js

You’ll see timestamps printed every minute.

Step 5: Advanced Usage

1. Create Tasks with Real Logic

js
cron.schedule('0 0 * * *', () => {
  console.log('Running database cleanup...');
  // Your cleanup logic here
});

2. Add Error Handling

js
cron.schedule('* * * * *', async () => {
  try {
    console.log('Running task...');
    throw new Error('Simulated error');
  } catch (err) {
    console.error('Cron job failed:', err.message);
  }
});

3. Integrate with APIs or Databases

js
const axios = require('axios');

cron.schedule('0 * * * *', async () => {
  try {
    const res = await axios.get('https://api.example.com/data');
    console.log('Data fetched:', res.data);
  } catch (err) {
    console.error('Fetch failed:', err.message);
  }
});

4. Start/Stop Tasks Dynamically

js
const task = cron.schedule('*/10 * * * * *', () => {
  console.log('Runs every 10 seconds');
});

task.stop();   // Pause
task.start();  // Resume

Best Practices

  • Use dotenv for cron expressions
  • Add logging (e.g., pino, winston)
  • Send alerts on failures (email, Slack, Discord)
  • For large workflows, use agenda, Bull, or Temporal

Conclusion

Using node-cron, you can automate workflows in Node.js with minimal setup. Whether you’re scheduling cleanup scripts, syncing external APIs, or generating reports, cron jobs make automation clean and reliable. This guide gives you everything needed to build robust scheduled tasks.