node-cron — Task Scheduler for Node.js

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 execute JavaScript functions on a schedule using the cron expression syntax from UNIX systems. It is ideal for automating routine tasks: cache clearing, sending email newsletters, database backups, or server monitoring.

Why do you need a task scheduler?

In web applications, you often need to execute code at a specific time, not just in response to a user request. Instead of using external services (like cron on the server), node-cron works directly inside your Node.js process. This simplifies deployment, does not require configuring a system scheduler, and is ideal for containerized applications (Docker, Kubernetes).

Installation

Installation via npm is done with a single command:

npm install node-cron

After installation, the library is ready to use — no additional dependencies are required.

Main Features

  • Flexible scheduling — support for standard cron patterns (minutes, hours, days, months, days of the week).
  • Start and stop — each task can be started or stopped on demand.
  • Error handling — you can set a callback for logging errors without crashing the application.
  • Simple syntax — only two methods: schedule and validate.

Code Example in JavaScript (Node.js)

Let's create a task that prints the current time to the console every minute:

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

// Task runs every minute: '* * * * *'
cron.schedule('* * * * *', () => {
console.log('Task executed:', new Date().toLocaleString());
});

console.log('Scheduler started. Press Ctrl+C to exit.');

A more complex example — sending a report every day at 8 AM:

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

cron.schedule('0 8 * * *', () => {
console.log('Sending daily report...');
// Here you call the email sending function
}, {
scheduled: true,
timezone: 'Europe/Moscow'
});

Validating a cron expression:

const isValid = cron.validate('*/5 * * * *');
console.log(isValid); // true

When to use node-cron?

  • Backup automation — creating a database dump every night.
  • Periodic cleanup — deleting outdated sessions or temporary files.
  • Monitoring — checking service availability and sending alerts.
  • Newsletters — sending emails on a schedule (e.g., digests).
  • Cache updates — rebuilding the cache during off-peak hours.

The node-cron library is suitable for projects of any size — from simple scripts to microservice architectures. It requires no external dependencies and works stably even during long uptime.

Recommendations