A lightweight task scheduler for Node.js applications that enables scheduling and execution of tasks using full crontab syntax
npx @tessl/cli install tessl/npm-node-cron@4.2.0Node Cron is a lightweight task scheduler for Node.js applications that enables scheduling and execution of tasks using full crontab syntax. It provides both CommonJS and ES6 module support with TypeScript definitions, allowing for flexible integration into any Node.js project.
npm install node-cronimport cron from "node-cron";Named imports:
import { schedule, validate, getTasks, getTask, createTask, ScheduledTask, TaskFn, TaskContext, TaskOptions } from "node-cron";For CommonJS:
const cron = require("node-cron");import cron from "node-cron";
// Schedule a task to run every minute
const task = cron.schedule('* * * * *', () => {
console.log('Running every minute');
});
// Schedule a background task
const backgroundTask = cron.schedule('0 0 * * *', './tasks/daily-backup.js', {
timezone: 'America/New_York'
});
// Validate a cron expression
const isValid = cron.validate('0 0 * * *');
console.log(isValid); // true
// Control tasks
task.stop();
task.start();
task.destroy();Core functionality for scheduling tasks using cron expressions.
function schedule(
expression: string,
func: TaskFn | string,
options?: TaskOptions
): ScheduledTask;The schedule function creates and starts a task that executes according to the provided cron expression. It accepts either an inline function or a file path to a background task module.
Creates a task without immediately starting it.
function createTask(
expression: string,
func: TaskFn | string,
options?: TaskOptions
): ScheduledTask;Note: This is an internal function that is exported but primarily used by the schedule function.
Validates cron expressions to ensure correct syntax.
function validate(expression: string): boolean;Returns true if the cron expression is valid, false otherwise.
Functions for managing scheduled tasks.
function getTasks(): Map<string, ScheduledTask>;
function getTask(taskId: string): ScheduledTask | undefined;getTasks returns all registered tasks, while getTask retrieves a specific task by its ID.
Resolves file paths for background tasks.
function solvePath(filePath: string): string;Note: This is an internal utility function used by the scheduler to resolve task file paths. It's exported but not intended for direct use by library consumers.
All scheduled tasks implement the ScheduledTask interface for consistent task management.
interface ScheduledTask {
id: string;
name?: string;
start(): void | Promise<void>;
stop(): void | Promise<void>;
getStatus(): string | Promise<string>;
destroy(): void | Promise<void>;
execute(): Promise<any>;
getNextRun(): Date | null;
on(event: TaskEvent, fun: (context: TaskContext) => Promise<void> | void): void;
off(event: TaskEvent, fun: (context: TaskContext) => Promise<void> | void): void;
once(event: TaskEvent, fun: (context: TaskContext) => Promise<void> | void): void;
}The getStatus() method returns one of the following string values:
type TaskStatus = 'stopped' | 'idle' | 'running' | 'destroyed';'stopped': Task is created but not started, or has been manually stopped'idle': Task is running and waiting for the next scheduled execution'running': Task is currently executing'destroyed': Task has been permanently destroyed and cannot be restartedExample usage:
const task = cron.schedule('* * * * *', () => {
console.log('Task running');
});
console.log(task.getStatus()); // 'idle'
task.stop();
console.log(task.getStatus()); // 'stopped'
task.destroy();
console.log(task.getStatus()); // 'destroyed'Tasks emit events throughout their lifecycle for monitoring and debugging.
type TaskEvent =
| 'task:started'
| 'task:stopped'
| 'task:destroyed'
| 'execution:started'
| 'execution:finished'
| 'execution:failed'
| 'execution:missed'
| 'execution:overlap'
| 'execution:maxReached';Example event handling:
const task = cron.schedule('* * * * *', () => {
console.log('Task executed');
});
task.on('execution:started', (context) => {
console.log('Task started at:', context.date);
});
task.on('execution:failed', (context) => {
console.error('Task failed:', context.execution?.error);
});Configuration options for customizing task behavior.
type TaskOptions = {
timezone?: string;
name?: string;
noOverlap?: boolean;
maxExecutions?: number;
maxRandomDelay?: number;
};timezone: Specify timezone for task execution (e.g., 'America/New_York')name: Custom name for the task (defaults to generated ID)noOverlap: Prevent overlapping executions if previous task is still runningmaxExecutions: Maximum number of times the task should executemaxRandomDelay: Add random delay (in ms) before executionExample with options:
const task = cron.schedule('0 9 * * *', () => {
console.log('Daily morning task');
}, {
timezone: 'Europe/London',
name: 'morning-routine',
noOverlap: true,
maxExecutions: 30
});Function signature for inline task functions.
type TaskFn = (context: TaskContext) => any | Promise<any>;Context object provided to task functions and event handlers.
type TaskContext = {
date: Date;
dateLocalIso: string;
task?: ScheduledTask;
execution?: Execution;
triggeredAt: Date;
};date: The scheduled execution date (timezone-adjusted if specified)dateLocalIso: ISO 8601 formatted local date and timetask: Reference to the scheduled taskexecution: Details about the current executiontriggeredAt: Actual time the event was triggeredDetails about a specific task execution.
type Execution = {
id: string;
reason: 'invoked' | 'scheduled';
startedAt?: Date;
finishedAt?: Date;
error?: Error;
result?: any;
};Node-cron supports standard cron syntax with optional seconds field:
# ┌────────────── second (optional)
# │ ┌──────────── minute
# │ │ ┌────────── hour
# │ │ │ ┌──────── day of month
# │ │ │ │ ┌────── month
# │ │ │ │ │ ┌──── day of week
# │ │ │ │ │ │
# │ │ │ │ │ │
# * * * * * *| field | value |
|---|---|
| second | 0-59 |
| minute | 0-59 |
| hour | 0-23 |
| day of month | 1-31 |
| month | 1-12 (or names) |
| day of week | 0-7 (or names, 0 or 7 are sunday) |
// Every minute
cron.schedule('* * * * *', task);
// Every hour at minute 30
cron.schedule('30 * * * *', task);
// Daily at 2:30 AM
cron.schedule('30 2 * * *', task);
// Weekly on Sunday at midnight
cron.schedule('0 0 * * 0', task);
// Monthly on the 1st at midnight
cron.schedule('0 0 1 * *', task);
// With seconds: every 30 seconds
cron.schedule('*/30 * * * * *', task);For background tasks, provide a file path instead of a function:
// Background task file (./tasks/backup.js)
module.exports = (context) => {
console.log('Running backup at:', context.date);
// Perform backup operations
};
// Schedule the background task
const backgroundTask = cron.schedule('0 2 * * *', './tasks/backup.js');Background tasks run in separate child processes, providing isolation from the main application.
Tasks can handle errors through event listeners:
const task = cron.schedule('* * * * *', () => {
throw new Error('Something went wrong');
});
task.on('execution:failed', (context) => {
console.error('Task failed:', context.execution?.error?.message);
// Optionally stop or restart the task
if (context.execution?.error?.message.includes('critical')) {
task.destroy();
}
});Tasks can be executed manually regardless of their schedule:
const task = cron.schedule('0 0 * * *', () => {
console.log('Daily task');
});
// Execute immediately
task.execute().then(result => {
console.log('Manual execution completed:', result);
}).catch(error => {
console.error('Manual execution failed:', error);
});