Task Scheduling & Cron Jobs - Automating Recurring Background Tasks in Node.js

Many backend tasks must occur on automated schedules: generating midnight invoice reports, expiring inactive user trials, emailing daily digests, and cleaning temporary directories. In this tutorial, you will master automated task scheduling using node-cron.

Cron Syntax Reference

 ┌────────────── minute (0 - 59)
 │ ┌──────────── hour (0 - 23)
 │ │ ┌────────── day of month (1 - 31)
 │ │ │ ┌──────── month (1 - 12)
 │ │ │ │ ┌────── day of week (0 - 7, 0 and 7 are Sunday)
 │ │ │ │ │
 * * * * *

Scheduling Automated Tasks with node-cron

npm install node-cron
// scheduler.js
const cron = require('node-cron');
const fs = require('fs');

console.log('[SCHEDULER INITIALIZED] Watching automated tasks...');

// 1. Run every minute (For testing)
cron.schedule('* * * * *', () => {
  console.log('[CRON 1 MINUTE] Heartbeat check:', new Date().toLocaleTimeString());
});

// 2. Run every midnight at 00:00 (Daily database cleanup)
cron.schedule('0 0 * * *', async () => {
  console.log('[MIDNIGHT TASK] Cleaning expired authentication tokens...');
  // await Token.deleteMany({ expiresAt: { $lt: new Date() } });
});

// 3. Run every Monday at 9:00 AM (Weekly student report)
cron.schedule('0 9 * * 1', () => {
  console.log('[WEEKLY TASK] Generating university attendance summary...');
});

Frequently Asked Questions (FAQ) - Student & Interview Review

Q1. What is node-cron and how do cron expressions work?

node-cron is a pure JavaScript task scheduler for Node.js based on GNU crontab. Cron expressions consist of 5 fields: 'minute (0-59) hour (0-23) day-of-month (1-31) month (1-12) day-of-week (0-7)' (e.g. '0 0 * * *' runs every midnight).

Q2. Why shouldn't you run heavy CPU cron tasks directly inside your main Express process?

If a scheduled cron task takes 30 seconds of heavy CPU calculation, it blocks the single-threaded event loop, freezing all user HTTP traffic for 30 seconds. Offload scheduled tasks to Worker Threads or a standalone background worker service using BullMQ and Redis.

Q3. What is BullMQ in Node.js?

BullMQ is a production-grade, distributed job and message queue library built on Redis. It provides delayed jobs, retries with exponential backoff, rate limiting, and parent-child task workflows for enterprise background worker systems.

Explore Related Node.js Tutorials & Next Steps

Boost your server-side JavaScript proficiency by studying these closely connected core modules:

Microservices & Message Queues

Integrate background jobs with RabbitMQ or Redis.

File System Module

Automate daily log rotation and file cleanups.

Performance Profiling

Ensure cron jobs don't block main event thread.

Share Share on Facebook Share on Twitter Share on LinkedIn Pin on Pinterest Share on Stumbleupon Share on Tumblr Share on Reddit Share on Diggit

You may also like this!