Scheduling Tasks with Cron in Node.js

How to use cron expressions in JavaScript applications for task scheduling.

javascriptnodejscode

Cron in Node.js

Schedule recurring tasks in your Node.js applications.

node-cron

Simple and popular cron library.

npm install node-cron
import cron from 'node-cron';

// Run every minute
cron.schedule(' ', () => {
console.log('Running every minute');
});

// Run every day at midnight
cron.schedule('0 0
', () => {
console.log('Running daily cleanup');
});

// With timezone
cron.schedule('0 9 ', () => {
console.log('9 AM in New York');
}, {
timezone: 'America/New_York'
});

// Validate expression
const isValid = cron.validate('
'); // true

cron-parser

Parse and iterate cron expressions.

npm install cron-parser
import parser from 'cron-parser';

// Parse expression
const interval = parser.parseExpression('/5 ');

// Get next occurrences
console.log(interval.next().toString());
console.log(interval.next().toString());

// With options
const interval2 = parser.parseExpression('0 9
', {
currentDate: new Date(),
tz: 'America/New_York'
});

Bull (Redis-based)

For distributed job queues.

import Queue from 'bull';

const myQueue = new Queue('tasks', { redis: { port: 6379 } });

// Add repeating job
await myQueue.add(
{ task: 'cleanup' },
{ repeat: { cron: '0 0 *' } }
);

// Process jobs
myQueue.process(async (job) => {
console.log('Processing:', job.data);
});