Skip to content

Scheduling Tasks and Background Jobs with node-cron

Beginning of the lesson

Scheduling Tasks and Background Jobs with node-cron

Run recurring work on a timetable instead of waiting for a request to trigger it

Big idea: Most real APIs need work that no user ever asks for directly: clearing expired sessions at 3 a.m., emailing a daily summary, retrying failed payments every ten minutes, or polling a partner service. A scheduled job runs on a clock you define, in the background, separate from your request handlers. The node-cron library lets you express that clock with a familiar cron string and hand it a function to run.
By the end you will be able to:
  • 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.

Continue this lesson on YourAIZone

The full lesson has the complete explanation, worked examples, common mistakes, tests with instant checking and an AI tutor. Start right away as a guest, or create an account to keep your progress.

In the full lesson

  • The complete explanation
  • Worked examples
  • Common mistakes and how to avoid them
  • Test questions: 15
  • AI tutor that answers questions about the topic
  • Progress tracking for students, parents and teachers