Node.js Cron Job Scheduler
The `cron` library for Node.js provides a robust solution for scheduling tasks (functions or external commands) using the familiar cron syntax, with support for second-level precision. The current stable version is 4.4.0, demonstrating active development with regular patch and minor releases, alongside beta releases for upcoming major versions like v5. Key differentiators include its flexibility in defining schedules using cron strings, standard JavaScript `Date` objects, or `Luxon DateTime` objects, comprehensive TypeScript support, and features for managing job lifecycle (start, stop, handling unexpected termination). It is designed for long-running Node.js applications and has evolved through major versions, introducing stricter cron pattern adherence and API refinements.
Common errors
-
Error: Your Node.js version (16.x.x) is not supported. Please upgrade to Node.js >=18.x.
cause Attempting to run `cron` v4 or later with an unsupported Node.js version.fixUpgrade your Node.js environment to version 18 or higher. Use `nvm install 18 && nvm use 18` or similar version management tools. -
TypeError: Cannot set property running of #<CronJob> which has only a getter
cause Attempting to directly assign a value to the deprecated `job.running` property in `cron` v4 or later.fixUse `job.start()` to initiate the job and `job.stop()` to pause it. The job's active status can be checked via `job.isActive` (read-only). -
Error: Value out of range for month (0-11)
cause Migrating from `cron` v2 to v3 without updating month indexes (e.g., still using '0' for January instead of '1').fixAdjust your cron patterns to use 1-12 for months (1=January, 12=December) and 0-7 for day-of-week (0 or 7=Sunday) as per v3 changes. -
TypeError: CronJob is not a constructor
cause Incorrect CommonJS `require` syntax for `CronJob` or attempting to use a default import for a named export.fixFor CommonJS, use `const { CronJob } = require('cron');`. For ESM, use `import { CronJob } from 'cron';`. Ensure it's a named import. -
TypeError: Cannot read properties of undefined (reading 'from')
cause Attempting to use the `CronJob.from()` static method on a version of `cron` prior to v3, or if the `CronJob` object itself is undefined due to incorrect import.fixEnsure you are on `cron` v3 or newer to use `CronJob.from()`. Verify `CronJob` is correctly imported and available.
Warnings
- breaking Node.js v16 is no longer supported by `cron` v4 and above. Projects must upgrade their Node.js environment to v18 or newer.
- breaking The `job.running` property was renamed to `job.isActive` in v4 and became read-only. Attempts to set `job.running` will fail.
- breaking Month indexing changed from `0-11` to `1-12`, and day-of-week indexing now supports `7` as Sunday (in addition to `0`).
- breaking The `CronJob` constructor in v3 no longer accepts a single object as its first parameter. Instead, use positional arguments or the `CronJob.from(argsObject)` static method.
- breaking The ability to execute system commands via string-based inputs, relying on `child_process`, has been removed in v5 to improve browser compatibility. This functionality will no longer be available.
- gotcha Asynchronous `onTick` functions in older versions might not correctly catch errors, leading to silent failures or unexpected behavior.
Install
-
npm install cron -
yarn add cron -
pnpm add cron
Imports
- CronJob
const CronJob = require('cron').CronJob;import { CronJob } from 'cron'; - CronTime
const CronTime = require('cron').CronTime;import { CronTime } from 'cron'; - CronJobParameters
import type { CronJobParameters } from 'cron';
Quickstart
import { CronJob } from 'cron';
// This job runs every second, logging a message to the console.
// The cronTime pattern '* * * * * *' specifies: second, minute, hour, day of month, month, day of week.
const job = new CronJob(
'* * * * * *', // cronTime: run every second
function () {
const now = new Date();
console.log('You will see this message every second:', now.toLocaleTimeString());
}, // onTick: function to execute when the job runs
null, // onComplete: function to execute when the job stops (optional)
true, // start: boolean to start the job immediately
'America/Los_Angeles' // timeZone: specify a timezone (optional)
);
console.log('Cron job scheduled and started. It will log a message every second. Press Ctrl+C to stop the process.');
// You can stop the job at any time using job.stop().
// For example, to stop after 10 seconds:
// setTimeout(() => {
// job.stop();
// console.log('Cron job stopped after 10 seconds.');
// }, 10000);