node-cron: JavaScript Task Scheduler

Online Python Trainer for Beginners

Learn Python easily without overwhelming theory. Solve practical tasks with automatic checking, get hints in Russian, and write code directly in your browser — no installation required.

Start Course

What is node-cron?

node-cron is a lightweight library for Node.js that allows you to run JavaScript functions (tasks) on a schedule using cron expression syntax. It is an analog of the Unix system scheduler cron, but works inside your application.

Why is it needed?

The library is necessary for automating routine server operations: database cleanup, sending email newsletters, creating backups, cache updates, data parsing, and any other periodic tasks. This eliminates the need to write your own timers and manage time intervals manually.

Installation

Installation is done via npm or yarn:

npm install node-cron

or

yarn add node-cron

Main Features

  • Simple syntax: uses standard cron expressions (minutes, hours, days, etc.)
  • Flexibility: support for seconds, optional timezone, execution on weekdays/weekends
  • Task management: methods start(), stop(), destroy() for execution control
  • Lightweight: no external dependencies required, library size is minimal

Code Example in JavaScript (Node.js)

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

// Task: print a message every minutecron.schedule('* * * * *', () => { console.log('Task runs every minute');});

// Task: every day at 9:30 AMcron.schedule('30 9 * * *', () => { console.log('Daily task at 9:30');});

// Task: every Monday at 8:00cron.schedule('0 8 * * 1', () => { console.log('Monday, 8:00 — time for the report');});

// Task with seconds: every 10 secondscron.schedule('*/10 * * * * *', () => { console.log('10 seconds have passed');});

// Stop the task after 5 secondsconst task = cron.schedule('*/1 * * * * *', () => { console.log('Infinite task');});setTimeout(() => { task.stop(); console.log('Task stopped');}, 5000);

When to Use

Use node-cron when you need to execute code at a specific time or with a set periodicity inside a Node.js application. It is ideal for:

  • regular cleanup of temporary files or logs;
  • sending notifications or emails on a schedule;
  • synchronizing data with external APIs;
  • generating reports in the background;
  • running tests or server health checks.

The library is not suitable for high-load distributed systems (a task queue is better), but for most typical scenarios, it is the optimal solution.

Recommendations