Back to results for “Background Jobs & Queues”
Node.js › Background Jobs & Queues

What is a cron job, and how would you schedule recurring background tasks in a Node.js application using node-cron or BullMQ's repeatable jobs?

Intermediate

Answer

A cron job runs on a fixed, recurring schedule defined by a cron expression (minute, hour, day-of-month, month, day-of-week) -- in Node.js this can be implemented with a lightweight in-process library like node-cron for simple single-instance schedulers, or via a queue system's built-in repeatable job support (like BullMQ), which is more reliable in a horizontally-scaled deployment since it avoids the same scheduled job firing redundantly from every running instance.
const cron = require('node-cron');

// Runs every day at 2:00 AM
cron.schedule('0 2 * * *', async () => {
  await generateDailyReport();
});

// BullMQ repeatable job, safe across multiple instances
await reportQueue.add('daily-report', {}, { repeat: { pattern: '0 2 * * *' } });
Real-world example A SaaS platform running five load-balanced server instances switches its daily-report generation from node-cron (which would fire the job five times simultaneously, once per instance) to a BullMQ repeatable job, ensuring the report is generated exactly once regardless of how many application instances are running.

Common follow-ups: Why does a naive node-cron setup break down specifically once an application scales to multiple instances?;How do you handle a scheduled job that's still running when its next scheduled trigger time arrives?