Croner: JavaScript Cron Scheduler
Croner is a zero-dependency JavaScript library designed for scheduling and executing functions based on cron expressions across all JavaScript environments, including Node.js (v18.0+) and modern browsers. The current stable version is 10.0.1, with a consistent release cadence for bug fixes and minor enhancements, as indicated by recent development builds. A major differentiator is its full compliance with OCPS 1.4, offering advanced scheduling capabilities like an optional seventh field for year specification and robust handling of complex cron patterns. Version 10 introduced features such as the `match()` method for pattern validation, `dayOffset` for relative scheduling, and improved DST fall-back behavior. It stands out for its isomorphic design and comprehensive feature set without external dependencies, providing a reliable and lightweight solution for various task scheduling needs.
Common errors
-
TypeError: Cron is not a constructor
cause Attempting to import Croner using CommonJS `require()` syntax in an environment configured for ESM, or incorrectly using a default import when it's a named export.fixUse ESM named import: `import { Cron } from 'croner';`. Ensure your project is configured for ESM if targeting modern Node.js environments (e.g., `"type": "module"` in `package.json`). -
Property 'nextRuns' does not exist on type 'Cron'.
cause This TypeScript error can occur if you are on `croner@10.0.0` due to a distribution issue with its type definitions, or if your TypeScript configuration is out of date.fixUpgrade to `croner@10.0.1` or later. Ensure your `tsconfig.json` targets a sufficiently modern JavaScript version and module system. -
Error: Invalid cron pattern: '<your-pattern>'
cause The provided cron expression is malformed, uses non-standard syntax not supported by OCPS 1.4, or conflicts with stricter parsing introduced in v10 (e.g., for 'L' or 'W' modifiers).fixVerify your cron pattern against OCPS 1.4 specifications. Pay attention to valid ranges, characters, and field counts (up to 7 fields including year). If you need more permissive parsing for legacy patterns, consider adding `{ sloppyRanges: true }` to your Cron options. -
Cron job did not fire at the expected time (or fired multiple times unexpectedly)
cause Common causes include incorrect timezone configuration, misunderstanding DST transition behavior (especially for fall-back), or issues with 'once' jobs created too close to their scheduled time.fixSpecify the `timezone` option explicitly (e.g., `{ timezone: 'America/New_York' }`). Review DST behavior changes in v10.0.2-dev.0. For 'once' jobs, ensure `allowPast: true` is set if the job might be initialized after its nominal start time.
Warnings
- breaking Version 10.0.0 introduced significant changes, including full OCPS 1.4 compliance with optional seventh field for years, `dayOffset`, and the new `match()` method. Existing cron patterns or configurations relying on previous parsing rules might need review, particularly if they implicitly relied on behaviors now covered by stricter OCPS compliance or `sloppyRanges`.
- breaking Daylight Saving Time (DST) fall-back scheduling behavior changed in 10.0.2-dev.0 (and subsequent stable releases). Specific-time patterns (e.g., `0 30 2 * * *`) now run once at the first occurrence during the overlap, while high-frequency patterns (e.g., `* * * * * *`) continue executing through the overlap period without gaps. This might alter expected execution times during DST transitions.
- gotcha The initial 10.0.0 release had TypeScript definition distribution issues, potentially leading to compilation errors. This was promptly fixed in 10.0.1.
- gotcha For 'once' jobs, the `allowPast` option is critical. If a job is created at or near its scheduled time and that time has already passed according to system clock, it might not fire. The `allowPast` option (introduced in 10.0.2-dev.1) addresses this by allowing such jobs to fire immediately.
- gotcha Cron jobs configured with the `protect` option might stop entirely if an error thrown within the `catch` callback is not handled. This behavior was addressed in 10.0.0-dev.8.
Install
-
npm install croner -
yarn add croner -
pnpm add croner
Imports
- Cron
const Cron = require('croner');import { Cron } from 'croner'; - CronOptions
import type { CronOptions } from 'croner'; - CronJob
import type { CronJob } from 'croner';
Quickstart
import { Cron } from 'croner';
// Schedule a job to run every minute
const job = new Cron('* * * * *', () => {
console.log(`Cron job executed at ${new Date().toISOString()}`);
});
// Schedule a job to run once on a specific date in the future
const oneTimeJob = new Cron(new Date(Date.now() + 1000 * 60 * 5), () => {
console.log(`One-time job executed after 5 minutes at ${new Date().toISOString()}`);
oneTimeJob.stop(); // Stop the job after it runs once
}, { timezone: 'Europe/Stockholm', name: 'One-Time Task' });
// Enumerate upcoming runs
console.log('Next 5 runs for the minute job:', job.nextRuns(5).map(d => d.toISOString()));
// Stop the minute job after 10 minutes for demonstration
setTimeout(() => {
job.stop();
console.log('Cron job stopped after 10 minutes.');
}, 1000 * 60 * 10);