### Automatic vs. Manual Job Start Source: https://github.com/kelektiv/node-cron/blob/main/_autodocs/configuration.md Demonstrates how to configure a job to start automatically upon creation or to manually start it later. ```typescript // Auto-start const job1 = new CronJob('0 0 * * *', () => {}, null, true); // Manual start const job2 = new CronJob('0 0 * * *', () => {}); job2.start(); ``` -------------------------------- ### Clone and Setup node-cron Repository Source: https://github.com/kelektiv/node-cron/blob/main/CONTRIBUTING.md Clone your fork of the node-cron repository, set up the upstream remote, and install project dependencies. Ensure your Node.js version matches the project's development version using nvm. ```bash # Clone your fork of the repo into the current directory $ git clone git@github.com:/node-cron.git # or https://github.com//node-cron.git for HTTPS # Navigate to the newly cloned directory $ cd node-cron # Assign the original repo to a remote called "upstream" $ git remote add upstream git@github.com:kelektiv/node-cron.git # or https://github.com/kelektiv/node-cron.git for HTTPS # Switch your node version to the version defined by the project as the development version # This step assumes you have already installed and configured https://github.com/nvm-sh/nvm # You may need to run `nvm install` if you have not already installed the development node version $ nvm use # Install the dependencies $ npm install ``` -------------------------------- ### onComplete Callback/Command Examples Source: https://github.com/kelektiv/node-cron/blob/main/_autodocs/configuration.md Examples for the onComplete callback, which can be a function, command string, or command object. ```typescript // Function () => { console.log('Job stopped'); } // Command string 'send-alert "Job completed"' // Command object { command: 'curl', args: ['-X', 'POST', 'http://example.com/done'] } ``` -------------------------------- ### Install Node-Cron Source: https://github.com/kelektiv/node-cron/blob/main/_autodocs/README.md Install the node-cron package using npm. ```bash npm install cron ``` -------------------------------- ### CronJob Parameters Usage Example Source: https://github.com/kelektiv/node-cron/blob/main/_autodocs/types.md Demonstrates how to construct a CronJob using the CronJobParams interface. Ensure all required properties like cronTime and onTick are provided, along with optional configurations like start, timeZone, and name. ```typescript import { CronJob, CronJobParams } from 'cron'; const params: CronJobParams = { cronTime: '0 9 * * 1-5', onTick: () => console.log('9am'), start: true, timeZone: 'America/New_York', name: 'morning-job' }; const job = CronJob.from(params); ``` -------------------------------- ### TypeScript Example with CronJob Source: https://github.com/kelektiv/node-cron/blob/main/_autodocs/README.md Demonstrates how to import and use CronJob, CronJobParams, and CronCallback types from the 'cron' library in TypeScript. Shows basic instantiation and a callback function example. ```typescript import { CronJob, CronJobParams, CronCallback } from 'cron'; const params: CronJobParams = { ... }; const job = CronJob.from(params); const callback: CronCallback = function() { // this is CronJob instance this.start(); }; ``` -------------------------------- ### Examples Source: https://github.com/kelektiv/node-cron/blob/main/_autodocs/INDEX.md Collection of real-world code examples demonstrating various use cases of node-cron, including basic scheduling, asynchronous operations, error handling, and dynamic job management. ```APIDOC ## Examples ### Description Provides practical code examples showcasing diverse applications of node-cron. ### Use Cases - **Basic Scheduling**: Daily, weekday, interval-based jobs. - **Async Operations**: Handling long-running tasks, preventing overlaps. - **Error Handling**: Implementing custom error handlers, graceful degradation. - **System Commands**: Executing external scripts, database tasks. - **Context and State**: Managing job state, multiple callbacks. - **Dynamic Management**: Creating jobs based on configuration, updating schedules. - **Monitoring**: Tracking execution, predicting future runs. - **Production Patterns**: Graceful shutdown, health checks. - **One-time Execution**: Scheduling for specific dates or relative times. ``` -------------------------------- ### RunOnInit Configuration Example Source: https://github.com/kelektiv/node-cron/blob/main/_autodocs/configuration.md Configuring a job to execute its onTick callback immediately upon construction. ```typescript const job = new CronJob( '0 0 * * *', () => { console.log('Running'); }, null, true, // start 'UTC', null, true // runOnInit - fires immediately and at midnight daily ); ``` -------------------------------- ### Basic CronJob Usage Source: https://github.com/kelektiv/node-cron/blob/main/_autodocs/README.md Create and start a CronJob with a cron expression, a callback function, and a timezone. The job starts immediately. ```typescript import { CronJob } from 'cron'; // Create and start a job const job = new CronJob( '0 0 * * *', // Cron expression: daily at midnight () => { console.log('Job executed'); }, null, // onComplete callback true, // start immediately 'UTC' // timezone ); ``` -------------------------------- ### Cron Expression Examples Source: https://github.com/kelektiv/node-cron/blob/main/_autodocs/api-reference/crontime.md See practical examples of cron expressions for various scheduling scenarios, from daily midnight tasks to specific times on weekdays or every few seconds. ```text `0 0 * * *` | Midnight every day (Unix cron: 5 fields) ``` ```text `0 0 0 * * *` | Midnight every day (6 fields with explicit seconds) ``` ```text `0 9 * * 1-5` | 9:00 AM, Monday-Friday ``` ```text `0 0 29 2 *` | Leap day (Feb 29), midnight ``` ```text `*/5 * * * * *` | Every 5 seconds ``` ```text `0 */4 * * *` | Every 4 hours at minute 0 ``` ```text `30 18 * * 5` | Friday, 6:30 PM ``` ```text `0 0 1 jan *` | January 1st, midnight ``` -------------------------------- ### Node-Cron Job Starting Flow Source: https://github.com/kelektiv/node-cron/blob/main/_autodocs/ARCHITECTURE.md Describes the sequence of events when a job is started using job.start(). It details timeout calculations, including handling delays exceeding MAXDELAY, and the use of setTimeout. ```plaintext 1. User calls job.start() 2. _isActive = true 3. Calculate timeout to next execution 4. If timeout > MAXDELAY: - Set remaining = timeout - MAXDELAY - timeout = MAXDELAY 5. setTimeout(callbackWrapper, timeout) 6. If unrefTimeout: timeout.unref() ``` -------------------------------- ### IntRange Examples Source: https://github.com/kelektiv/node-cron/blob/main/_autodocs/types.md Illustrates the output of the IntRange utility type, showing how it creates unions of integers within specified bounds. ```typescript // IntRange<0, 60> produces 0 | 1 | 2 | ... | 59 // IntRange<1, 13> produces 1 | 2 | 3 | ... | 12 ``` -------------------------------- ### Create Cron Job with Constructor Source: https://github.com/kelektiv/node-cron/blob/main/README.md Instantiate a CronJob using its constructor. The job starts automatically if the `start` parameter is true. Ensure the `cronTime` and `onTick` functions are correctly defined. ```javascript import { CronJob } from 'cron'; const job = new CronJob( '* * * * * *', // cronTime function () { console.log('You will see this message every second'); }, onComplete: null, true, // start 'America/Los_Angeles' // timeZone ); // job.start() is optional here because of the fourth parameter set to true. ``` -------------------------------- ### onTick Function Examples Source: https://github.com/kelektiv/node-cron/blob/main/_autodocs/configuration.md Examples of functions that can be used for the onTick callback. Supports both synchronous and asynchronous functions. ```typescript () => { console.log('Executing'); } async () => { await someTask(); } ``` -------------------------------- ### UTC Offset Configuration Example Source: https://github.com/kelektiv/node-cron/blob/main/_autodocs/configuration.md Specifying a UTC offset in minutes for schedule calculations, an alternative to timeZone. ```typescript new CronJob( '0 9 * * *', () => {}, null, true, null, // timeZone (not set) null, false, -300 // utcOffset: UTC-5 ); ``` -------------------------------- ### TimeUnit Array Example Source: https://github.com/kelektiv/node-cron/blob/main/_autodocs/types.md Demonstrates the usage of the `TimeUnit` type, which represents valid cron time field names. This example shows how to create an array of all possible time units. ```typescript import { TimeUnit } from 'cron'; const units: TimeUnit[] = [ 'second', 'minute', 'hour', 'dayOfMonth', 'month', 'dayOfWeek' ]; function formatField(unit: TimeUnit, value: number): string { switch (unit) { case 'month': return new Date(2025, value - 1).toLocaleString('en', { month: 'long' }); case 'dayOfWeek': return ['Sun', 'Mon', 'Tue', 'Wed', 'Thu', 'Fri', 'Sat'][value]; default: return String(value); } } ``` -------------------------------- ### TimeUnitField Example (Day of Week) Source: https://github.com/kelektiv/node-cron/blob/main/_autodocs/types.md Demonstrates the `TimeUnitField` type for representing days of the week. This example shows how to represent specific days like Monday, Wednesday, and Friday. ```typescript // Internal representation of "mon,wed,fri" (days 1,3,5) const dayOfWeekField: TimeUnitField<'dayOfWeek'> = { 1: true, 3: true, 5: true }; ``` -------------------------------- ### Cron Expression Examples Source: https://github.com/kelektiv/node-cron/blob/main/_autodocs/configuration.md Examples of cron expression strings for scheduling jobs. These define the timing of job execution. ```typescript '0 0 * * *' // Daily at midnight '0 9 * * 1-5' // Weekdays at 9am '0 0 * * 0' // Sundays at midnight '*/5 * * * * *' // Every 5 seconds '0 0 0 1 1 *' // January 1st at midnight (also: '@yearly') ``` -------------------------------- ### onTick Command String Examples Source: https://github.com/kelektiv/node-cron/blob/main/_autodocs/configuration.md Executing shell commands directly as strings for the onTick callback. ```typescript 'backup.sh' 'npm run backup' 'tar -czf /backups/db.tar.gz /data' ``` -------------------------------- ### Timezone Configuration Example Source: https://github.com/kelektiv/node-cron/blob/main/_autodocs/configuration.md Specifying a timezone for schedule calculations using IANA timezone strings. ```typescript new CronJob( '0 9 * * *', () => {}, null, true, 'America/New_York' // 9am in New York timezone ); ``` -------------------------------- ### Cron Expression Example Source: https://github.com/kelektiv/node-cron/blob/main/_autodocs/README.md Demonstrates the basic cron expression format with seconds, minutes, hours, day of month, month, and day of week. ```cron 0-59 0-59 0-23 1-31 1-12 0-7 (0 or 7 = Sunday) ``` -------------------------------- ### TimeUnitField Example (Minutes) Source: https://github.com/kelektiv/node-cron/blob/main/_autodocs/types.md Illustrates the `TimeUnitField` type, used for the internal representation of parsed cron fields. This example shows how to represent a minute field with specific values. ```typescript import { TimeUnitField } from 'cron'; // Internal representation of "0,15,30,45" minutes const minuteField: TimeUnitField<'minute'> = { 0: true, 15: true, 30: true, 45: true }; ``` -------------------------------- ### Create Cron Job with Static 'from' Method Source: https://github.com/kelektiv/node-cron/blob/main/README.md Use the static `CronJob.from()` method for a more readable way to create a CronJob by passing an object with configuration options. This method also supports automatic job start if `start` is set to true. ```javascript // equivalent job using the "from" static method, providing parameters as an object const job = CronJob.from({ cronTime: '* * * * * *', onTick: function () { console.log('You will see this message every second'); }, start: true, timeZone: 'America/Los_Angeles' }); ``` -------------------------------- ### CronJob with String Command (Echo) Source: https://github.com/kelektiv/node-cron/blob/main/_autodocs/types.md Example of creating a CronJob that executes a simple echo command. Useful for testing or basic notifications. ```typescript new CronJob('0 0 * * *', 'echo "Backup complete"', null, true); ``` -------------------------------- ### Commit Message Header Example Source: https://github.com/kelektiv/node-cron/blob/main/CONTRIBUTING.md Illustrates the standard format for a commit message header, including type, scope, and subject. ```commit fix(pencil): stop graphite breaking when too much pressure applied ``` -------------------------------- ### onTick Command Object Example Source: https://github.com/kelektiv/node-cron/blob/main/_autodocs/configuration.md Executing shell commands using an object with command, arguments, and options for the onTick callback. ```typescript { command: 'tar', args: ['-czf', '/backups/db.tar.gz', '/data'], options: { cwd: '/var/lib', env: { LEVEL: '9' } } } ``` -------------------------------- ### Start a CronJob Instance Source: https://github.com/kelektiv/node-cron/blob/main/_autodocs/api-reference/cronjob.md Starts the job execution. Has no effect if already running. Calculates timeout to next scheduled execution and sets internal timers. Handles sleep periods exceeding Node's `setTimeout` maximum by splitting into multiple timeout calls. ```typescript const job = new CronJob('0 0 * * *', () => { console.log('Midnight'); }, null, false); // start=false // Later, start the job job.start(); console.log(job.isActive); // true ``` -------------------------------- ### Update Dependencies and Get Latest Changes Source: https://github.com/kelektiv/node-cron/blob/main/CONTRIBUTING.md Before making changes, ensure your local environment is up-to-date. This involves checking out the main branch, pulling the latest changes, removing old dependencies, and reinstalling them. ```bash $ git checkout main $ git pull upstream main $ rm -rf node_modules $ nvm use $ npm install ``` -------------------------------- ### CronOnCompleteCallback Usage Example Source: https://github.com/kelektiv/node-cron/blob/main/_autodocs/types.md Demonstrates the basic usage of the onComplete callback when creating a new CronJob. This callback is executed after the job has been stopped. ```typescript import { CronJob } from 'cron'; new CronJob( '0 0 * * *', () => { console.log('Daily backup'); }, () => { console.log('Cleanup and shutdown'); }, true ); ``` -------------------------------- ### CronCallback Usage Examples Source: https://github.com/kelektiv/node-cron/blob/main/_autodocs/types.md Illustrates the usage of CronCallback with different configurations: without onComplete, with a custom context object, and with the onComplete parameter enabled. ```typescript import { CronCallback } from 'cron'; // Without onComplete const callback1: CronCallback = function() { console.log('This is the CronJob:', this); }; // With custom context interface MyContext { count: number; } const callback2: CronCallback = function() { this.count++; console.log('Count:', this.count); }; // With onComplete parameter const job = new CronJob( '0 * * * * *', function(onComplete) { console.log('Running'); onComplete?.(); }, () => { console.log('Stopped'); } ); ``` -------------------------------- ### CronTime Constructor Examples Source: https://github.com/kelektiv/node-cron/blob/main/_autodocs/api-reference/crontime.md Instantiate CronTime with a cron expression and timezone, a cron expression and UTC offset, a Date object for a one-time execution, or a Luxon DateTime object with a specified timezone. ```typescript import { CronTime } from 'cron'; // Cron expression with timezone const time1 = new CronTime('0 0 * * *', 'America/Los_Angeles'); ``` ```typescript // Cron expression with UTC offset const time2 = new CronTime('0 9 * * 1-5', null, -300); // UTC-5 ``` ```typescript // One-time execution at a specific Date const date = new Date('2025-12-25T10:30:00'); const time3 = new CronTime(date); ``` ```typescript // One-time execution via Luxon DateTime import { DateTime } from 'luxon'; const dt = DateTime.fromISO('2025-12-25T10:30:00'); const time4 = new CronTime(dt, 'UTC'); ``` -------------------------------- ### Graceful Shutdown with Cron Jobs Source: https://github.com/kelektiv/node-cron/blob/main/_autodocs/README.md This example shows how to ensure cron jobs complete their in-flight operations before the process exits, using `waitForCompletion` and handling SIGTERM signals. ```typescript const job = new CronJob( '0 0 * * *', async () => { await longOperation(); }, null, true, 'UTC', null, false, null, true, // unrefTimeout: allow process to exit true // waitForCompletion: wait for in-flight work ); process.on('SIGTERM', async () => { console.log('Shutting down...'); await job.stop(); // Waits for completion process.exit(0); }); ``` -------------------------------- ### Configure CronJob with Error Handler Source: https://github.com/kelektiv/node-cron/blob/main/_autodocs/configuration.md Example of initializing a CronJob with a custom error handler function passed as the seventh argument. ```typescript const job = new CronJob( '0 0 * * *', async () => { // Potential errors here const data = await fetch('/api/data'); process.send({ data }); }, null, true, 'UTC', null, false, null, false, false, (error) => { // Handle any error from onTick console.error('Job failed:', error); // Send alert, retry, update status, etc. } ); ``` -------------------------------- ### Weekday Schedule Source: https://github.com/kelektiv/node-cron/blob/main/_autodocs/README.md Schedule a task to run on weekdays (Monday to Friday) at a specific time. This example runs a task at 9:00 AM. ```typescript new CronJob( '0 9 * * 1-5', // Monday-Friday, 9:00 AM () => { console.log('Briefing'); }, null, true ); ``` -------------------------------- ### Commit Message with Issue Reference Example Source: https://github.com/kelektiv/node-cron/blob/main/CONTRIBUTING.md Demonstrates a commit message for a new feature that also references a GitHub issue to be closed. ```commit feat(pencil): add 'graphiteWidth' option Fix #42 ``` -------------------------------- ### Commit Message with Breaking Change Example Source: https://github.com/kelektiv/node-cron/blob/main/CONTRIBUTING.md Shows a commit message for a performance improvement that includes a breaking change and explains the reason. ```commit perf(pencil): remove graphiteWidth option BREAKING CHANGE: The graphiteWidth option has been removed. The default graphite width of 10mm is always used for performance reasons. ``` -------------------------------- ### Daily Task Schedule Source: https://github.com/kelektiv/node-cron/blob/main/_autodocs/README.md Schedule a task to run daily at a specific time. This example sets a task to run at 2:00 AM in the 'America/New_York' timezone. ```typescript new CronJob( '0 2 * * *', // 2:00 AM () => { console.log('Backup'); }, null, true, 'America/New_York' ); ``` -------------------------------- ### CronTime Field Storage Example (Minutes) Source: https://github.com/kelektiv/node-cron/blob/main/_autodocs/ARCHITECTURE.md Stores scheduled minutes as an object with keys set to `true` for efficient O(1) lookup, allowing quick checks for valid minute values. ```typescript // For "0,15,30,45" minutes minute = { 0: true, 15: true, 30: true, 45: true } ``` -------------------------------- ### CronJob with Object Constructor Source: https://github.com/kelektiv/node-cron/blob/main/_autodocs/README.md Create a CronJob using the object constructor for more declarative configuration. This example schedules a job for weekdays at 9am in the 'America/New_York' timezone. ```typescript import { CronJob } from 'cron'; const job = CronJob.from({ cronTime: '0 9 * * 1-5', // 9am weekdays onTick: () => { console.log('Morning briefing'); }, start: true, timeZone: 'America/New_York' }); ``` -------------------------------- ### CronJob Class Reference Source: https://github.com/kelektiv/node-cron/blob/main/_autodocs/INDEX.md Detailed reference for the CronJob class, including its constructor, static methods, instance methods, and properties. It covers parameter descriptions, factory methods, and common operations like starting, stopping, and managing callbacks. ```APIDOC ## CronJob Class ### Description Provides a reference for the CronJob class, detailing its constructor, factory methods, instance methods, and properties. ### Constructor - **Parameters**: Detailed descriptions, types, and defaults for all constructor parameters. ### Static Methods - **`from(options)`**: Factory method to create a CronJob instance from configuration options. ### Instance Methods - **`start()`**: Starts the cron job. - **`stop()`**: Stops the cron job. - **`addCallback(callback)`**: Adds a callback function to be executed on each tick. - **`setTime(cronTime)`**: Sets a new cron time for the job. - **`nextDate(date)`**: Calculates the next execution date after a given date. - **`nextDates(count)`**: Calculates a specified number of upcoming execution dates. - **`lastDate()`**: Returns the last execution date. - **`fireOnTick()`**: Manually triggers the onTick callback. ### Instance Properties - **`isActive`**: Boolean indicating if the job is currently active. - **`isCallbackRunning`**: Boolean indicating if a callback is currently running. - **Settable Properties**: Properties that can be modified after initialization (e.g., time, callbacks). ``` -------------------------------- ### CronTime Field Storage Example (Day of Week) Source: https://github.com/kelektiv/node-cron/blob/main/_autodocs/ARCHITECTURE.md Stores scheduled days of the week as an object with keys set to `true` for efficient O(1) lookup, enabling quick validation of matching days. ```typescript // For "1-5" days dayOfWeek = { 1: true, 2: true, 3: true, 4: true, 5: true } ``` -------------------------------- ### CronJob.start Source: https://github.com/kelektiv/node-cron/blob/main/README.md Initiates the job's execution. ```APIDOC ## CronJob.start ### Description Initiates the job's execution. ### Method Instance method ### Parameters None ### Returns None ``` -------------------------------- ### Configuration Reference Source: https://github.com/kelektiv/node-cron/blob/main/_autodocs/INDEX.md Detailed reference for configuring CronJob and CronTime, including all available parameters, their types, defaults, and descriptions. Covers cron expression formats, callback types, and timezone handling. ```APIDOC ## Configuration ### Description Provides a comprehensive reference for configuring node-cron jobs and times, including detailed explanations of all parameters and options. ### CronJob Constructor Parameters - **`cronTime`**: Format (cron syntax, Date, DateTime). - **`onTick`**: Command forms (function, string, object). - **`onComplete`**: Callback function. - **`start`**: Boolean, whether to start the job immediately. - **`timeZone`**: String, specifies the timezone. - **`context`**: Object, for binding context. - **`runOnInit`**: Boolean, whether to run on initialization. - **`utcOffset`**: Number or string, specifies UTC offset. - **`unrefTimeout`**: Boolean, controls process unreferencing. - **`waitForCompletion`**: Boolean, handles overlapping executions. - **`errorHandler`**: Function, custom error handling. - **`name`**: String, job identification. - **`threshold`**: Number, for missed deadline handling. ### CronTime Configuration - Details on cron expression format, syntax rules, aliases, and presets. - Explanation of Daylight Saving Time (DST) handling. ### Environment-based Configuration - Patterns for configuring node-cron using environment variables. ``` -------------------------------- ### Get Cron Job Execution Timeout Source: https://github.com/kelektiv/node-cron/blob/main/README.md Use `timeout` to get the remaining milliseconds until a cron expression's next execution. This is helpful for scheduling delays or monitoring. ```javascript import * as cron from 'cron'; const timeout = cron.timeout('0 0 * * *'); console.log(`The job would run in ${timeout}ms`); ``` -------------------------------- ### getNextDateFrom(start: Date | DateTime, timeZone?: string): DateTime Source: https://github.com/kelektiv/node-cron/blob/main/_autodocs/api-reference/crontime.md Computes the next execution time starting from a specified date, rather than from the current moment. This method is useful for custom scheduling logic and correctly handles daylight saving time transitions. ```APIDOC ## Instance Method: `getNextDateFrom(start: Date | DateTime, timeZone?: string): DateTime` ### Description Computes the next execution time starting from a specified date (not from now). Primarily used internally but available for custom scheduling logic. Handles daylight saving time transitions (both forward and backward jumps). ### Method `getNextDateFrom(start: Date | DateTime, timeZone?: string)` ### Parameters #### Path Parameters - **start** (Date | DateTime) - Required - Starting point for calculation. Can be current or past date. - **timeZone** (string) - Optional - Override timezone for calculation. ### Response #### Success Response - **DateTime** — Next execution time on or after the start date. ### Throws - `CronError` — If date is invalid or no execution found within 8 years. ### Example ```typescript import { DateTime } from 'luxon'; const time = new CronTime('0 0 * * *'); const jan1 = DateTime.fromISO('2025-01-01'); const nextMidnight = time.getNextDateFrom(jan1); console.log(nextMidnight.toISO()); // 2025-01-02T00:00:00 ``` ``` -------------------------------- ### One-Time Execution with CronJob Source: https://github.com/kelektiv/node-cron/blob/main/_autodocs/README.md Example of scheduling a cron job to execute only once at a specific date and time. ```typescript new CronJob( new Date('2025-12-25T10:30:00'), () => { console.log('Merry Christmas!'); }, null, true ); ``` -------------------------------- ### CronJob with System Command and Environment Options Source: https://github.com/kelektiv/node-cron/blob/main/_autodocs/types.md Create a CronJob to execute a system command with arguments and custom environment variables. The `options.env` property allows setting environment variables for the spawned process. ```typescript new CronJob('0 0 * * *', { command: '/usr/local/bin/backup.sh', args: ['--verbose'], options: { env: { ...process.env, BACKUP_TYPE: 'full' }, stdio: 'inherit' } }, null, true); ``` -------------------------------- ### Timezone Support in CronJob Source: https://github.com/kelektiv/node-cron/blob/main/_autodocs/README.md Example of scheduling a cron job to run at a specific time in a given IANA timezone. ```typescript new CronJob( '0 9 * * *', () => { console.log('9am'); }, null, true, 'Europe/London' // Any IANA timezone ); ``` -------------------------------- ### Lint and Format Code with ESLint and Prettier Source: https://github.com/kelektiv/node-cron/blob/main/CONTRIBUTING.md Run the linting process to check for code style issues and formatting errors. Most errors can be automatically fixed using the provided command. ```bash npm run lint ``` ```bash npm run lint:fix ``` -------------------------------- ### Cron Field Syntax Source: https://github.com/kelektiv/node-cron/blob/main/_autodocs/api-reference/crontime.md Learn the different syntaxes for defining cron fields, including wildcards, specific values, ranges, and steps. These allow for flexible scheduling of tasks. ```text `*` | Any value (all valid values for the field) | `*` matches all hours ``` ```text `1,3,5` | Specific values (comma-separated list) | `1,3,5` for Monday, Wednesday, Friday ``` ```text `1-5` | Range of values (inclusive) | `9-17` for 9am through 5pm ``` ```text `*/2` | Step (every Nth value) | `*/15` for every 15 minutes ``` ```text `1-10/2` | Range with step | `0-30/5` for 0, 5, 10, 15, 20, 25, 30 ``` -------------------------------- ### WaitForCompletion Configuration Example Source: https://github.com/kelektiv/node-cron/blob/main/_autodocs/configuration.md Preventing overlapping job executions by skipping scheduled fires while the callback is still running. ```typescript const job = new CronJob( '*/5 * * * * *', async () => { // Long-running async operation await longOperation(); }, null, true, 'UTC', null, false, null, false, true // waitForCompletion: prevent overlapping ); ``` -------------------------------- ### Executing System Commands with CronJob Source: https://github.com/kelektiv/node-cron/blob/main/_autodocs/README.md Shows how to configure a cron job to execute an external system command with arguments. ```typescript new CronJob( '0 0 * * *', { command: 'tar', args: ['-czf', '/backups/db.tar.gz', '/data'] }, null, true ); ``` -------------------------------- ### UnrefTimeout Configuration Example Source: https://github.com/kelektiv/node-cron/blob/main/_autodocs/configuration.md Enabling unrefTimeout allows the Node.js process to exit even if the job is still active. ```typescript // Background job that doesn't prevent shutdown const job = new CronJob( '0 0 * * *', () => { console.log('Cleanup'); }, null, true, 'UTC', null, false, null, true // unrefTimeout: allows graceful shutdown ); ``` -------------------------------- ### CronJob with Command String Source: https://github.com/kelektiv/node-cron/blob/main/_autodocs/types.md Instantiate a CronJob using a simple command string to be executed. The command will run at the scheduled time. ```typescript new CronJob('0 0 * * *', 'backup.sh', null, true); ``` -------------------------------- ### Cron Expression Presets Source: https://github.com/kelektiv/node-cron/blob/main/_autodocs/README.md Shows common cron presets for scheduling tasks at different frequencies. ```cron 0 0 0 1 1 * ``` ```cron 0 0 0 1 * * ``` ```cron 0 0 0 * * 0 ``` ```cron 0 0 0 * * * ``` ```cron 0 0 * * * * ``` ```cron 0 * * * * * ``` ```cron * * * * * * ``` ```cron 0 0 0 * * 1-5 ``` ```cron 0 0 0 * * 0,6 ``` -------------------------------- ### CronJob Configuration Object (from() static method) Source: https://github.com/kelektiv/node-cron/blob/main/_autodocs/configuration.md Instantiate a CronJob using the `from()` static method with a configuration object. This method allows for named properties, improving readability. Note that `timeZone` and `utcOffset` are mutually exclusive. ```typescript CronJob.from({ cronTime, onTick, onComplete, start, timeZone, // or utcOffset, not both context, runOnInit, unrefTimeout, waitForCompletion, errorHandler, name, threshold }) ``` -------------------------------- ### Custom Context Binding Example Source: https://github.com/kelektiv/node-cron/blob/main/_autodocs/configuration.md Setting a custom 'this' context for callback functions, allowing access to specific properties and methods. ```typescript const context = { counter: 0, increment() { this.counter++; } }; new CronJob( '* * * * * *', function() { this.counter++; // this is the context object console.log(this.counter); }, null, true, 'UTC', context ); ``` -------------------------------- ### Get Cron Expression String Source: https://github.com/kelektiv/node-cron/blob/main/_autodocs/api-reference/crontime.md The `toString()` method returns the cron expression as a string, useful for debugging or displaying the configured schedule. ```typescript const time = new CronTime('0,30 9 * * 1-5'); console.log(time.toString()); // '0,30 9 * * 1-5' ``` -------------------------------- ### Get Last Execution Time Source: https://github.com/kelektiv/node-cron/blob/main/_autodocs/api-reference/cronjob.md Retrieves the Date object of the most recent execution for a CronJob. Returns null if the job has never executed. ```typescript const job = new CronJob('* * * * * *', () => {}, null, true); // Immediately after first execution setTimeout(() => { console.log(job.lastDate()); // Date object of ~1 second ago }, 1500); ``` -------------------------------- ### CronJob with npm Script Source: https://github.com/kelektiv/node-cron/blob/main/_autodocs/types.md Instantiate a CronJob to run an npm script. Specify the command as 'npm', arguments for the script, and working directory options. ```typescript new CronJob('0 0 * * *', { command: 'npm', args: ['run', 'backup'], options: { cwd: '/app' } }, null, true); ``` -------------------------------- ### Cron Preset Patterns Source: https://github.com/kelektiv/node-cron/blob/main/_autodocs/api-reference/crontime.md Utilize predefined cron patterns for common scheduling needs, such as yearly, monthly, weekly, daily, and hourly executions. ```text `@yearly` | `0 0 0 1 1 *` | January 1st, midnight ``` ```text `@monthly` | `0 0 0 1 * *` | 1st of every month, midnight ``` ```text `@weekly` | `0 0 0 * * 0` | Every Sunday, midnight ``` ```text `@daily` | `0 0 0 * * *` | Every day, midnight ``` ```text `@hourly` | `0 0 * * * *` | Every hour ``` ```text `@minutely` | `0 * * * * *` | Every minute ``` ```text `@secondly` | `* * * * * *` | Every second ``` ```text `@weekdays` | `0 0 0 * * 1-5` | Monday-Friday, midnight ``` ```text `@weekends` | `0 0 0 * * 0,6` | Saturday-Sunday, midnight ``` -------------------------------- ### CronJob Constructor Source: https://github.com/kelektiv/node-cron/blob/main/_autodocs/api-reference/cronjob.md Initializes a new CronJob instance. This constructor accepts a wide range of parameters to customize the job's schedule, execution behavior, and error handling. ```APIDOC ## CronJob Constructor ### Description Initializes a new CronJob instance with a specified cron time, a tick callback, and various optional parameters for advanced configuration. ### Signature (Positional Arguments) ```typescript constructor( cronTime: string | Date | DateTime, onTick: CronCommand>, onComplete?: OC, start?: boolean | null, timeZone?: string | null, context?: C, runOnInit?: boolean | null, utcOffset?: null, unrefTimeout?: boolean | null, waitForCompletion?: boolean | null, errorHandler?: ((error: unknown) => void) | null, name?: string | null, threshold?: number | null ) ``` ### Parameters #### `cronTime` - **Type**: `string | Date | DateTime` - **Required**: Yes - **Description**: Cron expression, JavaScript Date, or Luxon DateTime. Cron expressions use 6 fields: second minute hour day-of-month month day-of-week. Seconds field is optional and defaults to 0. #### `onTick` - **Type**: `CronCommand>` - **Required**: Yes - **Description**: Function, system command string, or command object to execute at scheduled time. If `onComplete` is provided, the callback receives it as an argument. #### `onComplete` - **Type**: `OC` - **Default**: `undefined` - **Required**: No - **Description**: Callback invoked when job is stopped via `stop()` or when `runOnce` completes. Receives no arguments. #### `start` - **Type**: `boolean | null` - **Default**: `false` - **Required**: No - **Description**: If `true`, starts the job immediately after construction. Otherwise, call `start()` explicitly. #### `timeZone` - **Type**: `string | null` - **Default**: System timezone - **Required**: No - **Description**: IANA timezone string (e.g., `'America/Los_Angeles'`, `'Europe/London'`). Cannot be combined with `utcOffset`. #### `context` - **Type**: `C` - **Default**: `this` (CronJob instance) - **Required**: No - **Description**: Execution context (`this` binding) for onTick and onComplete callbacks. If omitted, defaults to the CronJob instance. #### `runOnInit` - **Type**: `boolean | null` - **Default**: `false` - **Required**: No - **Description**: If `true`, fires `onTick` immediately upon construction, in addition to scheduled executions. #### `utcOffset` - **Type**: `number | null` - **Default**: `undefined` - **Required**: No - **Description**: UTC offset in minutes (e.g., `240` for UTC-4, `-330` for UTC+5:30). Cannot be combined with `timeZone`. #### `unrefTimeout` - **Type**: `boolean | null` - **Default**: `false` - **Required**: No - **Description**: If `true`, calls `unref()` on internal timers, allowing Node.js process to exit even if job is running. Useful for background jobs. #### `waitForCompletion` - **Type**: `boolean | null` - **Default**: `false` - **Required**: No - **Description**: If `true`, ensures only one `onTick` executes concurrently; subsequent scheduled fires are skipped if previous callback hasn't completed. #### `errorHandler` - **Type**: `((error: unknown) => void) | null` - **Default**: Console error logging - **Required**: No - **Description**: Custom error handler for exceptions in `onTick`. If not provided, errors are logged to console. #### `name` - **Type**: `string | null` - **Default**: `undefined` - **Required**: No - **Description**: Optional name for the job, used in debug messages and threshold warnings. #### `threshold` - **Type**: `number | null` - **Default**: `250` - **Required**: No - **Description**: Threshold in milliseconds. If execution deadline is missed by less than threshold, executes immediately with warning. If missed by more, skips execution with warning. Useful for handling delays on slow hardware. ``` -------------------------------- ### Handle ExclusiveParametersError with Conflicting Timezone/Offset Source: https://github.com/kelektiv/node-cron/blob/main/_autodocs/errors.md Example of catching an ExclusiveParametersError when both timeZone and utcOffset are specified in the CronJob constructor. This indicates a conflict in scheduling parameters. ```typescript import { CronJob, ExclusiveParametersError } from 'cron'; try { new CronJob( '0 0 * * *', () => {}, null, false, 'America/New_York', // timeZone null, false, -300 // utcOffset - ERROR! ); } catch (error) { if (error instanceof ExclusiveParametersError) { console.error(error.message); // "You can't specify both timeZone and utcOffset" } } ``` -------------------------------- ### Handle CronError with Invalid Syntax Source: https://github.com/kelektiv/node-cron/blob/main/_autodocs/errors.md Example of catching a CronError when an invalid cron expression syntax is provided. This typically occurs with too many or too few fields. ```typescript import { CronTime, CronError } from 'cron'; try { // Too many fields new CronTime('0 0 * * * * *'); } catch (error) { if (error instanceof CronError) { console.error(`Cron error: ${error.message}`); } } ``` -------------------------------- ### Creating Jobs from Configuration Object Source: https://github.com/kelektiv/node-cron/blob/main/_autodocs/examples.md Dynamically create CronJob instances using a configuration object and a helper function. This approach centralizes job definitions and includes validation for cron expressions. The `createJobFromConfig` function returns a `CronJob` instance or `null` if the schedule is invalid. ```typescript import { CronJob, validateCronExpression } from 'cron'; interface JobConfig { name: string; schedule: string; action: () => void | Promise; timezone?: string; runOnInit?: boolean; } function createJobFromConfig(config: JobConfig): CronJob | null { const validation = validateCronExpression(config.schedule); if (!validation.valid) { console.error(`Invalid schedule for ${config.name}: ${validation.error.message}`); return null; } return CronJob.from({ cronTime: config.schedule, onTick: config.action, start: true, timeZone: config.timezone || 'UTC', runOnInit: config.runOnInit || false, name: config.name, errorHandler: (error) => { console.error(`Job ${config.name} failed:`, error); } }); } // Usage const jobs = new Map(); const jobConfigs: JobConfig[] = [ { name: 'daily-backup', schedule: '0 0 * * *', action: async () => { await backup(); } }, { name: 'hourly-check', schedule: '0 * * * * *', action: () => { checkHealth(); } } ]; jobConfigs.forEach(config => { const job = createJobFromConfig(config); if (job) { jobs.set(config.name, job); } }); // Later: stop all jobs function stopAllJobs() { jobs.forEach(job => job.stop()); jobs.clear(); } ``` -------------------------------- ### One-time Execution with Date/DateTime Source: https://github.com/kelektiv/node-cron/blob/main/_autodocs/configuration.md Scheduling a job for a single execution using JavaScript Date or Luxon DateTime objects. ```typescript new CronJob(new Date('2025-12-25T10:30:00'), () => {}) // One-time execution new CronJob(DateTime.fromISO('2025-12-25T10:30:00'), () => {}) ``` -------------------------------- ### Check CronJob isActive Status Source: https://github.com/kelektiv/node-cron/blob/main/_autodocs/api-reference/cronjob.md Use the `isActive` property to determine if a CronJob has been started and not yet stopped. This reflects whether internal timers are actively running. ```typescript const job = new CronJob('0 0 * * *', () => {}, null, false); console.log(job.isActive); // false job.start(); console.log(job.isActive); // true job.stop(); console.log(job.isActive); // false ``` -------------------------------- ### CronJob Callback Execution Status Source: https://github.com/kelektiv/node-cron/blob/main/README.md The `isCallbackRunning` property of a CronJob instance indicates whether the `onTick` function is currently executing. It is `false` before starting and after completion, and `true` during execution. ```javascript 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); // false ``` -------------------------------- ### Schedule CronJob Relative to Now Source: https://github.com/kelektiv/node-cron/blob/main/_autodocs/examples.md Schedule a CronJob to execute after a specified delay in milliseconds. This is useful for tasks that need to run a short time after the script starts or in response to an event. ```typescript import { CronJob } from 'cron'; import { DateTime } from 'luxon'; function scheduleIn(milliseconds: number, callback: () => void) { const executeAt = DateTime.now().plus({ milliseconds }); return new CronJob( executeAt.toJSDate(), callback, null, true ); } // Usage scheduleIn(5000, () => { console.log('Executed 5 seconds from now'); }); ``` -------------------------------- ### Get Cron Job Execution Time Source: https://github.com/kelektiv/node-cron/blob/main/README.md Use `sendAt` to determine the exact Luxon DateTime when a cron expression will next execute. This function is useful for planning or logging. ```javascript import * as cron from 'cron'; const dt = cron.sendAt('0 0 * * *'); console.log(`The job would run at: ${dt.toISO()}`); ``` -------------------------------- ### Async Callbacks in CronJob Source: https://github.com/kelektiv/node-cron/blob/main/_autodocs/README.md Demonstrates using async/await within a cron job's callback function for asynchronous operations. ```typescript new CronJob( '0 0 * * *', async () => { const data = await fetch('/api/data'); await database.save(data); }, null, true ); ``` -------------------------------- ### Recurring Task Every N Minutes Source: https://github.com/kelektiv/node-cron/blob/main/_autodocs/README.md Schedule a task to run at a regular interval, such as every 15 minutes. The last parameter 'true' ensures the job starts automatically. ```typescript new CronJob( '*/15 * * * * *', // Every 15 minutes () => { console.log('Check'); }, null, true ); ``` -------------------------------- ### Create a New Topic Branch Source: https://github.com/kelektiv/node-cron/blob/main/CONTRIBUTING.md Create a new branch for your feature, bug fix, or improvement. This isolates your changes and makes them easier to manage. ```bash $ git checkout -b ``` -------------------------------- ### Get Milliseconds Until Next Execution Source: https://github.com/kelektiv/node-cron/blob/main/_autodocs/api-reference/crontime.md The `getTimeout()` method returns the number of milliseconds remaining until the next scheduled cron job execution. This value can be negative if the system is experiencing delays. ```typescript const time = new CronTime('0 12 * * *'); // Noon const msUntilNoon = time.getTimeout(); console.log(`${msUntilNoon}ms until next execution`); ``` -------------------------------- ### Push Your Topic Branch Source: https://github.com/kelektiv/node-cron/blob/main/CONTRIBUTING.md After making your code changes, push your topic branch to your fork. This makes your changes available for review. ```bash $ git push origin ``` -------------------------------- ### Calculate Next Execution Time Source: https://github.com/kelektiv/node-cron/blob/main/_autodocs/api-reference/crontime.md Call `sendAt()` on a `CronTime` instance to get the next scheduled execution time as a Luxon DateTime object. This method respects configured timezones. ```typescript const time = new CronTime('0 9 * * 1-5', 'America/New_York'); const nextRun = time.sendAt(); console.log(`Next execution: ${nextRun.toISO()}`); ``` -------------------------------- ### Pre-scheduling Checks with `sendAt` and `timeout` Source: https://github.com/kelektiv/node-cron/blob/main/_autodocs/api-reference/standalone-functions.md Utilize `cron.sendAt` to determine the next execution time and `cron.timeout` to get the milliseconds until the next trigger. Useful for monitoring or displaying upcoming schedules. ```typescript import * as cron from 'cron'; const expression = '0 0 * * *'; // Midnight daily // Check if next execution is too far away const nextRun = cron.sendAt(expression); const hoursAway = nextRun.diffNow('hours').hours; if (hoursAway > 24) { console.log(`Schedule won't run for ${hoursAway.toFixed(1)} hours`); } // Check milliseconds for monitoring const msUntilRun = cron.timeout(expression); console.log(`Polling every second, will trigger in ${msUntilRun}ms`); ``` -------------------------------- ### Use Named Jobs for Debugging and Monitoring Source: https://github.com/kelektiv/node-cron/blob/main/_autodocs/configuration.md Always provide a `name` for your jobs to simplify debugging and monitoring efforts. ```typescript name: `${jobType}-${environment}` // e.g., "backup-prod", "cleanup-dev" ```