MCPcopy Create free account
hub / github.com/Hexagon/croner

github.com/Hexagon/croner

Chat with this repo
repository ↗ · DeepWiki ↗ · release 11.1.0 ↗ · + Follow · compare 3 versions

Trigger functions or evaluate cron expressions in JavaScript or TypeScript. No dependencies. Most features. Node. Deno. Bun. Browser.

196 symbols 731 edges 44 files 124 documented · 63% ● updated 5d ago★ 2,6223 open issues

Browse by type

⨍ Functions 185◇ Types & classes 11
What it actually does AI analysis from the code graph — generated when you open this
loading…
README

Croner

Trigger functions or evaluate cron expressions in JavaScript or TypeScript. No dependencies. All features. Node. Deno. Bun. Browser.

Try it live on jsfiddle, and check out the full documentation on croner.56k.guru.

Croner - Cron for JavaScript and TypeScript

npm version JSR NPM Downloads No dependencies MIT License

Croner is available for JavaScript/TypeScript · Rust · Python · .NET · C++

  • Trigger functions in JavaScript using Cron syntax.
  • Evaluate cron expressions and get a list of upcoming run times.
  • Supports seconds and year fields, L (last), W (weekday), # (nth occurrence), and + (AND logic).
  • Works in Node.js >=18.0 (both require and import), Deno >=2.0 and Bun >=1.0.0.
  • Works in browsers as standalone, UMD or ES-module.
  • Target different time zones.
  • Built-in overrun protection
  • Built-in error handling
  • Includes TypeScript typings.
  • Support for asynchronous functions.
  • Pause, resume, or stop execution after a task is scheduled.
  • Operates in-memory, with no need for a database or configuration files.
  • Zero dependencies.

Quick examples:

// Basic: Run a function at the interval defined by a cron expression
const job = new Cron('*/5 * * * * *', () => {
    console.log('This will run every fifth second');
});

// Enumeration: What dates do the next 100 sundays occur on?
const nextSundays = new Cron('0 0 0 * * 7').nextRuns(100);
console.log(nextSundays);

// Days left to a specific date
const msLeft = new Cron('59 59 23 24 DEC *').nextRun() - new Date();
console.log(Math.floor(msLeft/1000/3600/24) + " days left to next christmas eve");

// Run a function at a specific date/time using a non-local timezone (time is ISO 8601 local time)
// This will run 2030-01-23 00:00:00 according to the time in Asia/Kolkata
new Cron('2030-01-23T00:00:00', { timezone: 'Asia/Kolkata' }, () => { console.log('Yay!') });

// Check if a date matches a cron pattern
const mondayCheck = new Cron('0 0 0 * * MON');
console.log(mondayCheck.match('2024-01-01T00:00:00')); // true  (Monday)
console.log(mondayCheck.match('2024-01-02T00:00:00')); // false (Tuesday)

More examples...

Installation

Full documentation on installation and usage is found at https://croner.56k.guru

Note If you are migrating from a different library such as cron or node-cron, or upgrading from a older version of croner, see the migration section of the manual.

Install croner using your favorite package manager or CDN, then include it in you project:

Using Node.js or Bun

// ESM Import ...
import { Cron } from "croner";

// ... or CommonJS Require, destructure to add type hints
const { Cron } = require("croner");

Using Deno

import { Cron } from "jsr:@hexagon/croner@11.1.0";

In a webpage using the UMD-module

<script src="https://cdn.jsdelivr.net/npm/croner@11.1.0/dist/croner.umd.js"></script>

Documentation

Signature

Cron takes three arguments

// Parameters
// - First: Cron pattern, js date object (fire once), or ISO 8601 time string (fire once)
// - Second: Options (optional)
// - Third: Function run trigger (optional)
const job = new Cron("* * * * * *", { maxRuns: 1 });

// If function is omitted in constructor, it can be scheduled later
job.schedule((job, /* optional */ context) => {});

The job will be sceduled to run at next matching time unless you supply option { paused: true }. The new Cron(...) constructor will return a Cron instance, later called job, which have a couple of methods and properties listed below.

Status

job.nextRun( /*optional*/ startFromDate );  // Get a Date object representing the next run.
job.nextRuns(10, /*optional*/ startFromDate ); // Get an array of Dates, containing the next n runs.
job.previousRuns(10, /*optional*/ referenceDate ); // Get an array of Dates, containing previous n scheduled runs.
job.enumerate( /*optional*/ startFromDate ); // Get a stateful CronIterator for use in for...of / destructuring.
job.msToNext( /*optional*/ startFromDate ); // Get the milliseconds left until the next execution.
job.currentRun();       // Get a Date object showing when the current (or last) run was started.
job.previousRun( );         // Get a Date object showing when the previous job was started.

job.match( date );      // Check if a Date object or date string matches the cron pattern (true or false).

job.isRunning();    // Indicates if the job is scheduled and not paused or killed (true or false).
job.isStopped();    // Indicates if the job is permanently stopped using `stop()` (true or false).
job.isBusy();       // Indicates if the job is currently busy doing work (true or false).

job.getPattern();   // Returns the original pattern string
job.getOnce();      // Returns the original run-once date (Date or null)
job.describe();     // Describes the pattern in words, e.g. "At 12:00, on Monday." Pass `swedish` or your own phrases for another language.

Control functions

job.trigger();      // Force a trigger instantly
job.pause();        // Pause trigger
job.resume();       // Resume trigger
job.stop();     // Stop the job completely. It is not possible to resume after this.
                // Note that this also removes named jobs from the exported `scheduledJobs` array.

Properties

job.name            // Optional job name, populated if a name were passed to options

Options

Key Default value Data type Remarks
name undefined String If you specify a name for the job, Croner will keep a reference to the job in the exported array scheduledJobs. The reference will be removed on .stop().
maxRuns Infinite Number
catch false Boolean|Function Catch unhandled errors in triggered function. Passing true will silently ignore errors. Passing a callback function will trigger this callback on error.
timezone undefined String Timezone in Europe/Stockholm format
startAt undefined String|Date Date, or ISO 8601 formatted datetime (2021-10-17T23:43:00)

in local time (according to the timezone or utcOffset option if passed). Inclusive, a run exactly at startAt is included (except when interval is set) | | stopAt | undefined | String|Date | Date, or ISO 8601 formatted datetime (2021-10-17T23:43:00)

in local time (according to the timezone or utcOffset option if passed). Exclusive, a run exactly at stopAt is not included | | interval | 0 | Number | Minimum number of seconds between triggers. | | paused | false | Boolean | If the job should be paused from start. | | context | undefined | Any | Passed as the second parameter to triggered function | | domAndDow | false | boolean | Combine day-of-month and day-of-week using true = AND, false = OR (default) | | legacyMode | (deprecated) | boolean | Deprecated: Use domAndDow instead. Inverse of domAndDow (legacyMode: true = domAndDow: false). | | unref | false | boolean | Setting this to true unrefs the internal timer, which allows the process to exit even if a cron job is running. | | utcOffset | undefined | number | Schedule using a specific utc offset in minutes. This does not take care of daylight savings time, you probably want to use option timezone instead. | | protect | undefined | boolean|Function | Enabled over-run protection. Will block new triggers as long as an old trigger is in progress. Pass either true or a callback function to enable | | alternativeWeekdays | false | boolean | Enable Quartz-style weekday numbering (1=Sunday, 2=Monday, ..., 7=Saturday). When false (default), uses standard cron format (0=Sunday, 1=Monday, ..., 6=Saturday). | | allowPast | false | boolean | If true, date-based jobs scheduled in the past will fire immediately. If false, only jobs scheduled within the past second will fire (to handle timing edge cases). | | dayOffset | 0 | number | Offset the scheduled date by a number of days. Positive values shift forward, negative values shift backward. For example, dayOffset: -1 schedules one day before the pattern match. nextRun(), nextRuns(), previousRuns(), msToNext(), enumerate(), startAt and stopAt all refer to the shifted run time. | | mode | "auto" | string | Controls how the cron pattern field count is interpreted. Options: "auto" (detect automatically), "5-part" (minute-level), "6-part" (second-level), "7-part" (second+year), "5-or-6-parts", "6-or-7-parts". | | sloppyRanges | false | boolean | If true, allows non-standard stepping formats for backward compatibility (e.g. /10, 5/5, 30/30). When false (default), only */step or min-max/step formats are allowed. | | fixedTimeRule | "single-value" | string | Which jobs are fixed-time jobs in DST handling. "single-value" (default, as croner-rust): a single value in each of seconds, minutes and hours. "no-wildcard" (closer to Vixie cron): no wildcard or step in seconds, minutes and hours, so lists and ranges such as 30 2,14 * * * count too. See Pattern. |

Warning Unreferencing timers (option unref) is only supported by Node.js and Deno. Browsers have not yet implemented this feature, and it does not make sense to use it in a browser environment.

Pattern

Croner uses Vixie Cron based expressions with the following powerful extensions:

// ┌──────────────── (optional) second (0 - 59)
// │ ┌────────────── minute (0 - 59)
// │ │ ┌──────────── hour (0 - 23)
// │ │ │ ┌────────── day of month (1 - 31)
// │ │ │ │ ┌──────── month (1 - 12, JAN-DEC)
// │ │ │ │ │ ┌────── day of week (0 - 6, SUN-Mon) 
// │ │ │ │ │ │       (0 to 6 are Sunday to Saturday; 7 is Sunday, the same as 0)
// │ │ │ │ │ │ ┌──── (optional) year (1 - 9999)
// │ │ │ │ │ │ │
// * * * * * * *
  • Optional second and year fields for enhanced precision:

    • 6-field format: SECOND MINUTE HOUR DAY-OF-MONTH MONTH DAY-OF-WEEK
    • 7-field format: SECOND MINUTE HOUR DAY-OF-MONTH MONTH DAY-OF-WEEK YEAR
    • Supported year range: 1-9999
  • Advanced calendar modifiers:

    • L: Last day of month or last occurrence of a weekday. L in day-of-month = last day of month; 5#L or FRI#L = last Friday of the month.
    • W: Nearest weekday. 15W triggers on the weekday closest to the 15th (moves to Friday if 15th is Saturday, Monday if 15th is Sunday). Won't cross month boundaries.
    • LW: Last weekday (Monday to Friday) of the month, in day-of-month. L and LW are values of their own, but can be items in a list: L,LW = the last day and the last weekday; 1W,15W,LW = the weekdays nearest the 1st and the 15th, and the last weekday. 5L and LW-5 are not valid.
    • #: Nth occurrence of a weekday. 5#2 = second Friday; MON#1 = first Monday of the month.
  • Enhanced logical control:

    • +: Explicit AND logic modifier. Prefix the day-of-week field with + to require both day-of-month AND day-of-week to match. Example: 0 12 1 * +MON only triggers when the 1st is also a Monday.
    • ?: Wildcard alias (behaves identically to *). Non-portable: Its use is discouraged in patterns intended for cross-system use. Supported in all fields for compatibility, but primarily meaningful in day-of-month and day-of-week fields.
    • DST handling, the same as croner-rust and based on Vixie cron, which deviates from OCPS 1.4 §4.3.1 (see below):
      • Fixed-time jobs, with a single value in each of seconds, minutes and hours by default (e.g. 0 30 2 * * *): A time that occurs twice (DST fall back) runs once, at the first occurrence. A time that doesn't exist (DST spring forward) runs at the first valid time after the gap, on the same day. When the gap ends at midnight (e.g. America/Nuuk on 30 March 2024, 23:00 -02:00 to 00:00 -01:00), no valid time is left on that day, and the run for that day is skipped.
      • Interval jobs, with a wildcard, step, range or list in seconds, minutes or hours (e.g. */5 * * * * or 0 30 1,2 * * *): A time that occurs twice runs on both occurrences, so the job keeps running through the repeated hour. A time that doesn't exist is skipp

Core symbols most depended-on inside this repo

browse all functions →

Shape

Method 115
Function 70
Class 8
Interface 3

Languages

TypeScript100%

Modules by API surface

src/croner.ts51 symbols
src/describe.ts39 symbols
src/date.ts27 symbols
src/pattern.ts20 symbols
src/helpers/timezone.ts15 symbols
src/options.ts4 symbols
src/utils.ts3 symbols
src/helpers/calendar.ts1 symbols

Dependencies from manifests, versioned

esbuild0.28.2 · 1×
rollup-plugin-dts6.5.1 · 1×
@cross/test1×
@std/assert1×
@typescript/typescript66.0.2 · 1×
rollup4.69.0 · 1×
tsx4.20.0 · 1×
typescript7.0.0 · 1×

For agents

$ claude mcp add --transport http codehub https://codehub.bot/mcp

One hosted endpoint, no key: your agent can search, read and trace Hexagon/croner and every other graph here. Cursor, Windsurf and other clients →

⬇ download graph artifact

Ask about this repo answers extend the page