Scheduling Tasks and Background Jobs with node-cron
Run recurring work on a timetable instead of waiting for a request to trigger it
node-cron library lets you express that clock with a familiar cron string and hand it a function to run.
- read and write five-field cron expressions;
- schedule, start, and stop a job with
node-cron; - stop overlapping runs of a slow job with a simple lock flag;
- explain why scheduled work belongs outside your request handlers;
- add a real nightly cleanup job to an existing Express API.
1. Why scheduled work exists
Your API spends most of its life reacting: a request arrives, you run a handler, you send a response. But plenty of important work has no request behind it. Nobody visits a URL to make yesterday's temporary files get deleted. Nobody clicks a button to send the 8 a.m. digest email. That work has to happen on a schedule — on a timetable your program keeps for itself.
Typical scheduled jobs you will meet in production:
- Cleanups — delete expired password-reset tokens, prune old logs, remove abandoned uploads.
- Reports — build a nightly sales summary and email it to the team.
- Reminders — notify users whose trial ends tomorrow.
- Polling — every few minutes, ask a payment provider whether pending charges have settled.
Analogy. Think of a building caretaker. Visitors (requests) come and go all day, and staff at the front desk (your route handlers) serve them. But the caretaker works to a timetable nobody asks about: empty the bins each night, check the boiler every morning, water the plants on Mondays. Scheduled jobs are the caretaker of your server — quiet, regular, and essential.
On Unix systems this timetable has a classic name: cron, a background daemon that runs commands at fixed times. node-cron brings that same idea inside your Node process, so you can schedule JavaScript functions without leaving your app or writing operating-system config.