croner

repository·master·Indexed 25 days ago

https://github.com/hexagon/croner

A zero-dependency cron implementation for JavaScript and TypeScript compatible with Node.js (>=18.0), Deno (>=2.0), Bun (>=1.0.0), and browsers. It supports OCPS 1.0-1.4 compliant syntax, including seconds, years, and advanced modifiers like L, W, #, and + logic. Key features include timezone support, overrun protection, and the ability to evaluate upcoming run times using the Cron class.

Tokens
10.1K
Snippets
24
Records
55
Agent score
82%

What's inside croner

  1. Overview of Croner features and compatibility

    master

    Croner is a zero-dependency cron implementation for JavaScript and TypeScript that supports:

    • Platforms: Node.js (>=18.0), Deno (>=2.0), Bun (>=1.0.0), and Browsers (Standalone, UMD, or ESM).
    • Compliance: OCPS 1.0-1.4 (supports seconds, years, L, W, #, and + logic).
    • Capabilities: Timezone support, built-in overrun protection, error handling, and support for asynchronous functions.
    • Lifecycle: Ability to pause, resume, or stop scheduled tasks.
    • Environment: Operates in-memory with no external database requirements.
  2. Use advanced calendar modifiers (L, W, #)

    master

    Croner supports advanced OCPS 1.3 modifiers for complex scheduling:

    • L (Last):
      • In Day of Month: Represents the last day of the month.
      • In Day of Week: Represents the last occurrence of a specific weekday. Example: 5#L or FRI#L is the last Friday of the month.
      • When used in a range, it affects all specified weekdays (e.g., 5-6#L is the last Friday and Saturday of the month).
    • W (Nearest Weekday): Triggers on the weekday closest to the specified day of the month. It will not cross month boundaries. Example: 15W triggers on the weekday closest to the 15th (e.g., if the 15th is Saturday, it triggers on Friday; if Sunday, it triggers on Monday).
    • # (Nth Occurrence): Specifies the Nth occurrence of a weekday in a month. Example: 5#2 is the second Friday; MON#1 is the first Monday.
  3. Find and manage named jobs via scheduledJobs

    master
    If you provide a name in the options object, the job is automatically added to the scheduledJobs array (accessible via Cron.scheduledJobs or by importing scheduledJobs). This allows you to find and control jobs from different scopes of your application. Note that calling .stop() removes the job from this array.
  4. Enforce AND logic for Day of Month and Day of Week

    master

    By default, Croner uses OR logic for the Day of Month and Day of Week fields (OCPS 1.0). For example, 0 20 1 * MON triggers on the 1st of the month OR on any Monday.

    To require that both conditions are met (OCPS 1.4), you can use one of two methods:

    1. The + modifier: Prefix the day-of-week field with +. Example: 0 12 1 * +MON only triggers when the 1st of the month is also a Monday.
    2. The domAndDow option: Pass { domAndDow: true } in the options object (the 2nd parameter of the scheduling function).
  5. Use advanced Cron patterns and modifiers

    master

    Croner supports Vixie Cron expressions with several powerful extensions:

    Field Formats

    • 6-field: SECOND MINUTE HOUR DAY-OF-MONTH MONTH DAY-OF-WEEK
    • 7-field: SECOND MINUTE HOUR DAY-OF-MONTH MONTH DAY-OF-WEEK YEAR (Year range: 1-9999)

    Advanced Modifiers

    • L: Last day of month (in Day-of-Month field) or last occurrence of a weekday (e.g., FRI#L).
    • W: Nearest weekday (e.g., 15W triggers on the weekday closest to the 15th).
    • #: Nth occurrence of a weekday (e.g., 5#2 is the second Friday).
    • +: Explicit AND logic. Prefix the Day-of-Week field with + to require both Day-of-Month AND Day-of-Week to match (e.g., 0 12 1 * +MON triggers only when the 1st is a Monday).
    • ?: Wildcard alias (behaves like *).

    Logical Behavior

    By default, Croner uses OR logic for Day-of-Month and Day-of-Week. To use AND logic, use the + modifier in the pattern or set { domAndDow: true } in the options.

    Quartz Mode

    Set alternativeWeekdays: true to use Quartz-style numbering: 1=Sunday, 2=Monday, ..., 7=Saturday. Standard mode uses 0=Sunday, ..., 6=Saturday.

  6. Create a Cron job with new Cron()

    master

    To create a new cron job, instantiate the Cron class. The constructor accepts three arguments:

    1. pattern: A cron pattern string (e.g., "* * * * * *").
    2. options (optional): An object for configuration, such as { maxRuns: 1 } or { paused: true }.
    3. callback (optional): The function to execute when the cron pattern matches.

    If you omit the callback in the constructor, you can schedule the function later using job.schedule().

    By default, the job is scheduled to run at the next matching time unless the { paused: true } option is provided.

    const job = new Cron(
        /* The pattern */
        "* * * * * *",
        /* Options (optional) */
        { maxRuns: 1 },
        /* Function (optional) */
        () => {}
    );
  7. Install Croner

    master

    Install Croner using your preferred package manager. It is compatible with Node.js (>=18.0), Deno (>=2.0), Bun (>=1.0.0), and browsers.

    Node.js or Bun

    Use ESM imports or CommonJS require.

    Deno

    Import from deno.land/x or jsr.io.

    Browser

    Include the UMD module via a <script> tag.

  8. Import Croner in Deno

    master

    For Deno, import Cron directly from deno.land/x or jsr.io. Ensure you replace $CRONER_VERSION with the actual version number (e.g., 10.0.1).

    // From deno.land/x
    import { Cron } from "https://deno.land/x/croner@$CRONER_VERSION/dist/croner.js";
    
    // ... or jsr.io
    import { Cron } from "jsr:@hexagon/croner@$CRONER_VERSION";
  9. Migrate from cron to Croner

    master

    To switch from the cron package to croner, follow these steps:

    1. Install Croner:

      npm install croner
    2. Update Imports: Croner uses named exports. Instead of const cron = require('cron'), use:

      const { Cron } = require('croner');

      If you want to maintain compatibility with existing code that expects a CronJob name, you can alias it:

      const { Cron as CronJob } = require('croner');
    3. Update Job Creation: The constructor is Cron, not CronJob. The signature typically involves the pattern, an optional options object, and the callback function.

      Example Migration:

      // Old (cron)
      cron.schedule('* * * * *', () => {
          console.log('Running a task every minute');
      }, { timezone: "Europe/Oslo" });
      
      // New (croner)
      new Cron('* * * * *', { timezone: "Europe/Oslo" }, () => {
          console.log('Running a task every minute');
      });
    // croner
    const { Cron } = require('croner');
    
    const job = new Cron('0 0 12 * * *', { /* options */ }, () => {
        console.log('This job will run at 12:00 PM every day.');
    });
    
    job.start();
  10. Schedule a one-time task with a Date or ISO 8601 string

    master

    Instead of a cron expression, you can pass a JavaScript Date object or an ISO 8601 formatted string as the pattern. The scheduled function will trigger exactly once at that specified time.

    If you are using a timezone different from the local timezone, pass the ISO 8601 local time for the target location and specify the timezone in the options object (the 2nd parameter).