Install cron via npm
mainTo use cron in your Node.js project, install it using npm:
npm install cronrepository·main·Indexed 27 days ago
https://github.com/kelektiv/node-cronA robust tool for running jobs (functions or commands) on schedules defined using the cron syntax in Node.js. Version 4.4.0 supports an enhanced 6-field cron format including seconds. It provides the CronJob class for task scheduling, CronTime for expression manipulation, and utility functions like validateCronExpression, sendAt, and timeout to predict execution times.
To use cron in your Node.js project, install it using npm:
npm install cronIf you are upgrading from version 3 to version 4, note the following breaking changes:
job.running property has been renamed to job.isActive.isActive is now read-only. To start or stop a job, use job.start() and job.stop() instead of attempting to set the property.When using node-cron, be aware of the following technical behaviors:
While the module allows specifying execution dates using JS Date or Luxon DateTime objects, standard cron syntax excludes millisecond precision. Due to computation delays, specifying a precise future execution time (e.g., adding exactly 1ms to the current time) may be inconsistent. Delays of less than 4-5 ms might lead to unexpected results.
this Context in onTickIf you use an arrow function for the onTick callback, it will be bound to the parent's this context. Consequently, the callback will not have access to the CronJob instance's this context. To access the cronjob instance via this, use a regular function instead.
The library provides standalone functions to predict when a cron pattern will trigger:
cron.sendAt(pattern): Returns a Luxon DateTime object indicating when the job will execute.cron.timeout(pattern): Returns a number representing the milliseconds until the next execution.import * as cron from 'cron';
const dt = cron.sendAt('0 0 * * *');
console.log(`The job would run at: ${dt.toISO()}`);
const timeout = cron.timeout('0 0 * * *');
console.log(`The job would run in ${timeout}ms`);Alternatively, use the CronJob.from() method to provide configuration as a single object. This is often cleaner for complex configurations.
import { CronJob } from 'cron';
const job = CronJob.from({
cronTime: '* * * * * *',
onTick: function () {
console.log('You will see this message every second');
},
start: true,
timeZone: 'America/Los_Angeles'
});Use validateCronExpression to check if a string follows the supported cron syntax. It returns an object containing a valid boolean and an error string if invalid.
import * as cron from 'cron';
const validation = cron.validateCronExpression('0 0 * * *');
console.log(`Is the cron expression valid? ${validation.valid}`);
if (!validation.valid) {
console.error(`Validation error: ${validation.error}`);
}Use the following methods and properties to control and monitor your jobs:
job.start(): Initiates the job.job.stop(): Halts the job.job.isActive (Read-only): Indicates if a job is active (checking if the callback needs to be called).job.isCallbackRunning (Read-only): Indicates if a callback is currently executing.const job = new CronJob('* * * * * *', async () => {
console.log(job.isCallbackRunning); // true during callback execution
await someAsyncTask();
console.log(job.isCallbackRunning); // still true until callback completes
});
console.log(job.isCallbackRunning); // false
job.start();
console.log(job.isActive); // true
console.log(job.isCallbackRunning); // falseYou can instantiate a CronJob by passing arguments directly to the constructor. The fourth parameter start determines if the job begins immediately. If start is false or omitted, you must call job.start() manually.
import { CronJob } from 'cron';
const job = new CronJob(
'* * * * * *', // cronTime
function () {
console.log('You will see this message every second');
}, // onTick
null, // onComplete
true, // start
'America/Los_Angeles' // timeZone
);The library supports an enhanced 6-field cron format (including seconds).
Fields:
second: 0-59minute: 0-59hour: 0-23day of month: 1-31month: 1-12 (or names like jan, feb)day of week: 0-7 (0 or 7 is Sunday, or names like mon, tue)Syntax:
*: Any value1-3,5: Ranges and individual values*/2: Steps (every two units)The CronJob constructor accepts several advanced configuration options:
onComplete: Invoked when the job is halted with job.stop().runOnInit: If true, triggers onTick immediately after initialization.waitForCompletion: If true, prevents new onTick executions until the current one finishes. New scheduled executions are skipped if they occur while a callback is running.errorHandler: Function to handle exceptions in onTick.threshold: Threshold in ms to control whether to execute or skip missed execution deadlines caused by slow hardware (default: 250).The onTick parameter accepts more than just functions. You can pass a string or an object to execute shell commands via child_process.spawn.
String format: 'command arg1 arg2'
Object format: { command: 'command', args: ['arg1'], options: {} }
You can create a new scheduled job using the CronJob constructor or the CronJob.from() static method. The job requires a cron expression (string) and an onTick callback that defines the task to run.
Constructor Parameters:
cronTime: A cron expression string.onTick: The task to execute. Can be a function, a command string (to be spawned), or a command object.onComplete (optional): A callback executed when the job is stopped.start (optional): Boolean to start the job immediately upon instantiation.timeZone (optional): A valid timezone string.context (optional): An object to be used as this context within the callbacks.runOnInit (optional): If true, the job executes immediately upon creation.utcOffset (optional): A UTC offset string (cannot be used with timeZone).unrefTimeout (optional): If true, the internal timer will not prevent the Node.js process from exiting.waitForCompletion (optional): If true, the job will wait for the current onTick execution to finish before starting the next one or stopping.errorHandler (optional): A function to handle errors thrown during execution.name (optional): A string identifier for the job.threshold (optional): The maximum allowed delay (in ms) for a missed execution before the job is skipped.