What is node-cron?
node-cron is a lightweight library for Node.js that allows you to execute JavaScript functions on a schedule using cron expression syntax. It is ideal for automating routine tasks: sending email notifications, cleaning databases, web scraping, or generating reports.
Why do you need a task scheduler?
In web development, it is often necessary to execute code not immediately, but at specific intervals. Manually running scripts with setInterval() or setTimeout() is inconvenient for complex schedules (for example, "every second Tuesday of the month at 15:00"). node-cron solves this problem by providing a flexible and readable way to set time.
Installation
Install the library via npm:
npm install node-cronOr use yarn:
yarn add node-cronMain Functions
- cron.schedule(expression, callback) — runs a function on a schedule.
- cron.validate(expression) — checks the validity of a cron expression.
- task.stop() — stops a task.
- task.start() — resumes execution of a stopped task.
- Support for seconds (an additional field at the beginning of the expression).
Code Example in JavaScript (Node.js)
Let's look at a simple example: running a task every minute that prints the current time to the console.
const cron = require('node-cron');
// Task runs every minuteconst task = cron.schedule('* * * * *', () => { console.log('Task started:', new Date().toLocaleTimeString());});
// Start the tasktask.start();
// Stop the task after 5 minutessetTimeout(() => { task.stop(); console.log('Task stopped');}, 300000);Decoding the cron expression: '* * * * *' — minute, hour, day of month, month, day of week. An asterisk means "every". For example, '0 9 * * 1-5' — every weekday at 9:00.
Example with validation:
const cron = require('node-cron');
const expression = '30 4 * * 0'; // every Sunday at 4:30 AMif (cron.validate(expression)) { cron.schedule(expression, () => { console.log('Sunday data cleanup...'); });} else { console.error('Invalid cron expression');}When to use node-cron?
- Backup automation: creating database backups once a day.
- Sending newsletters: daily digest mailing to subscribers.
- Monitoring: checking the availability of external APIs every 5 minutes.
- Cache cleanup: deleting outdated data from Redis or the file system.
- Data parsing: downloading currency exchange rates or news on a schedule.
The library is perfect for small and medium-sized projects where a full-fledged task orchestrator like Bull or Agenda is not needed. If your application runs on a single server and requires simple cron-like behavior, node-cron will be an excellent choice.