### v3 Task Creation with Scheduled and RunOnInit Source: https://www.nodecron.com/migrating-from-v3.html In v3, `scheduled` and `runOnInit` options controlled task startup behavior. This example shows a task scheduled to run every minute, starting immediately and executing once on initialization. ```javascript const task = cron.schedule('* * * * *', async () => { console.log('Running every minute'); }, { scheduled: true, runOnInit: true, timezone: 'America/Sao_Paulo' }); ``` -------------------------------- ### Install cron-translate Source: https://www.nodecron.com/blog/plain-english-to-cron.html Install the cron-translate library using npm. ```bash npm install cron-translate ``` -------------------------------- ### Install Fastify and node-cron Plugin Source: https://www.nodecron.com/fastify.html Install the necessary packages for Fastify, node-cron, and the Fastify plugin. These are peer dependencies, so your existing installations will be used. ```bash npm install @node-cron/fastify node-cron fastify ``` -------------------------------- ### Redis Coordinator Setup Source: https://www.nodecron.com/run-cron-jobs-across-multiple-servers.html Integrate a Redis coordinator for high availability. This allows multiple replicas to race for each task execution, with automatic failover if the primary instance goes down. Requires installing `@node-cron/redis-coordinator`. ```bash npm install @node-cron/redis-coordinator ``` ```javascript import { createClient } from 'redis'; import cron, { setRunCoordinator } from 'node-cron'; import { RedisLockCoordinator } from '@node-cron/redis-coordinator'; const redis = createClient(); await redis.connect(); setRunCoordinator(new RedisLockCoordinator(redis)); cron.schedule('0 3 * * *', runNightlyBackup, { name: 'nightly-backup', distributed: true, distributedLease: 5 * 60_000, }); ``` -------------------------------- ### Install node-cron Source: https://www.nodecron.com/getting-started.html Install the node-cron package using npm. This is the first step to using the library in your project. ```bash npm install node-cron ``` -------------------------------- ### Migrate CronJob to node-cron Task Source: https://www.nodecron.com/migrating-from-cron.html This example shows the transformation from a `cron` library `CronJob` setup to the modern `node-cron` task scheduling. It includes updating imports, using arrow functions for tasks, and configuring options like timezone and `noOverlap`. ```javascript const { CronJob } = require('cron'); const job = new CronJob( '0 0 3 * * *', async function () { try { await runBackup(); } catch (err) { console.error(err); } }, null, true, 'America/Sao_Paulo' ); ``` ```javascript import cron from 'node-cron'; const task = cron.schedule('0 0 3 * * *', () => runBackup(), { name: 'nightly-backup', timezone: 'America/Sao_Paulo', noOverlap: true, }); task.on('execution:failed', (ctx) => console.error(ctx.execution?.error)); ``` -------------------------------- ### Schedule a Task Every Minute Source: https://www.nodecron.com/ This is a basic example to schedule a task that runs every minute. It's a good starting point for simple recurring jobs. ```javascript import cron from 'node-cron'; // Day one: run something every minute. cron.schedule('* * * * *', () => { console.log('Hello from node-cron'); }); ``` -------------------------------- ### Install Redis Coordinator and Dependencies Source: https://www.nodecron.com/distributed-coordination.html Install the official Redis coordinator package and necessary dependencies for Redis integration with Node-Cron. ```bash npm install @node-cron/redis-coordinator node-cron redis ``` ```bash npm install @node-cron/redis-coordinator node-cron ioredis ``` -------------------------------- ### schedule(expression, func, options?) Source: https://www.nodecron.com/api-reference.html Creates a task and starts it immediately. Returns a ScheduledTask with control methods. ```APIDOC ## `schedule(expression, func, options?)` ### Description Creates a task and **starts it immediately**. Returns a `ScheduledTask`. ### Parameters Name| Type| Description ---|---|--- `expression`| `string`| A valid cron expression (e.g. "0 0 * * *" for daily at midnight). `func`| `Function | string`| A function to run, **or** a path to a module exporting a `task` function. A path creates a Background Task. `options`| `Options` _(optional)_| Execution options. See Scheduling Options. ### Options ```typescript type Options = { name?: string; // human-readable identifier timezone?: string; // e.g. "America/New_York" noOverlap?: boolean; // skip a run if the previous one is still going maxExecutions?: number; // destroy the task after N runs maxRandomDelay?: number; // jitter, in ms, added before each run logger?: Logger; // per-task logger (not for background tasks) suppressMissedWarning?: boolean // silence the "missed execution" warning missedExecutionTolerance?: number // ms a late run may still execute (default 1000) distributed?: boolean; // run on one instance per fire across a fleet runCoordinator?: RunCoordinator;// per-task coordinator (overrides the global one) distributedLease?: number; // lease ms for lease-based coordinators (default 30000) unref?: boolean; // don't keep the process alive for this task's timer }; ``` Background tasks accept two extra options, `executeTimeout` and `startTimeout`, documented in Background Tasks. See Scheduling Options for details and examples. ### Returns A `ScheduledTask` with control methods: ```javascript import cron from 'node-cron'; const task = cron.schedule('* * * * *', () => { console.log('Running every minute'); }); task.stop(); // pause the task task.start(); // start or resume it task.destroy(); // remove it permanently ``` > 🛈 For **inline** tasks these methods are synchronous (`void`); for **background** tasks they return a `Promise`. See Task Lifecycle. ``` -------------------------------- ### Node.js Background Task File Example Source: https://www.nodecron.com/run-background-jobs-in-nodejs.html This is an example of a task file that will be executed in a separate forked process. Heavy computations within this task will not block the main event loop. ```javascript // tasks/generate-report.js export function task() { // This runs in a separate process. // Heavy computation here won't block your HTTP server. return generateMonthlyReport(); } ``` -------------------------------- ### Create and manually start a cron task with node-cron Source: https://www.nodecron.com/migrating-from-cron.html Use `cron.createTask` for tasks that should not start immediately. You can then manually start the task later using the `start()` method. ```javascript const task = cron.createTask('0 */5 * * * *', () => doWork()); // later task.start(); ``` -------------------------------- ### v4 Task Creation - Default Immediate Start Source: https://www.nodecron.com/migrating-from-v3.html In v4, `scheduled` and `runOnInit` are removed. Tasks start immediately by default. To execute the function once after scheduling, call `task.execute()`. ```javascript const task = cron.schedule('* * * * *', async () => { console.log('Running every minute'); }, { timezone: 'America/Sao_Paulo' }); // Immediately run the task once, in addition to its schedule. task.execute(); ``` -------------------------------- ### v4 Task Creation - Manual Start with createTask Source: https://www.nodecron.com/migrating-from-v3.html To create a task that does not start on creation (equivalent to v3's `scheduled: false`), use `cron.createTask` and manually start it with `task.start()`. ```javascript const task = cron.createTask('* * * * *', async () => { console.log('This task is manually started'); }, { noOverlap: true }); // The task will not run until start() is called. task.start(); ``` -------------------------------- ### Quick Start: Registering Fastify Plugin with Tasks Source: https://www.nodecron.com/fastify.html Register the fastifyNodeCron plugin and define scheduled tasks. Jobs are created on registration and automatically start when Fastify is ready, and are destroyed on close. ```typescript import Fastify from 'fastify'; import { fastifyNodeCron } from '@node-cron/fastify'; const app = Fastify(); await app.register(fastifyNodeCron, { tasks: [ { cron: '0 3 * * *', // every day at 03:00 name: 'nightly-backup', run: async () => { await runBackup(); }, }, ], }); await app.listen({ port: 3000 }); ``` -------------------------------- ### Create a task and start it later Source: https://www.nodecron.com/usage-rules.html Use `cron.createTask` when you need to attach event listeners or inspect the task before starting it. You must explicitly call `.start()` to run the task. ```javascript const task = cron.createTask(0, 0, () => { console.log('I will be executed at midnight every day'); }); task.start(); ``` -------------------------------- ### English to Cron Examples Source: https://www.nodecron.com/cron-translate.html Demonstrates various English phrases and their corresponding cron expressions, covering different frequencies, times, and days. ```text Input| Cron ---|--- `every minute`| `0 * * * * *` `every 5 minutes`| `0 */5 * * * *` `every day at noon`| `0 0 12 * * *` `every weekday at 6pm`| `0 0 18 * * 1-5` `every monday at 9am`| `0 0 9 * * 1` `every weekend`| `0 0 0 * * 0,6` `last friday of the month`| `0 0 0 * * 5L` `first monday of the month at 9am`| `0 0 9 * * 1#1` ``` -------------------------------- ### start() Source: https://www.nodecron.com/task-lifecycle.html Starts the scheduler, moving the task from `stopped` to `idle`. It begins evaluating the cron expression and runs the function at matched times for inline tasks, or forks a dedicated process for background tasks. Has no effect if the task is already running. ```APIDOC ## start() ### Description Starts the scheduler, moving the task from `stopped` to `idle`. For inline tasks, it begins evaluating the cron expression and runs the function at matched times. For background tasks, it forks a dedicated process and starts a daemon that handles scheduling. This method has no effect if the task is already running. ### Method `start()` ### Parameters None ``` -------------------------------- ### Install @node-cron/nestjs and node-cron Source: https://www.nodecron.com/nestjs.html Install the @node-cron/nestjs package and its peer dependency node-cron. Ensure you are using a compatible version of node-cron. ```bash npm install @node-cron/nestjs node-cron ``` -------------------------------- ### English to Cron Examples with Values, Lists, and Ranges Source: https://www.nodecron.com/cron-translate.html Illustrates how to use values, lists, and ranges in English phrases to define specific minutes, days, months, and weekdays for cron expressions. ```text Example| Cron ---|--- `at minutes 0, 15, 30 and 45`| `0 0,15,30,45 * * * *` `at minute 1 to 30`| `0 1-30 * * * *` `between 9am and 5pm`| `0 0 9-17 * * *` `on day 1 to 10`| `0 0 0 1-10 * *` `in march and june`| `0 0 0 1 3,6 *` `on monday to friday`| `0 0 0 * * 1-5` ``` -------------------------------- ### Install node-cron and Uninstall cron Source: https://www.nodecron.com/migrating-from-cron.html Use npm to uninstall the `cron` package and install `node-cron`. ```bash npm uninstall cron npm install node-cron ``` -------------------------------- ### Create a cron task without immediate start Source: https://www.nodecron.com/api-reference.html Create a task that runs every hour but does not start automatically. It can be started later using task.start(). ```javascript import cron from 'node-cron'; const task = cron.createTask('0 * * * *', () => { console.log('Running every hour'); }); task.start(); ``` -------------------------------- ### Configuring Start Timeout for Background Tasks Source: https://www.nodecron.com/background-tasks.html Adjust `startTimeout` to allow more time for slow-loading task files to initialize. The default is 5000ms. ```javascript import cron from 'node-cron'; const task = cron.schedule('0 3 * * *', './tasks/backup.js', { startTimeout: 20_000, // allow a slow-loading task file more time to boot }); ``` -------------------------------- ### Schedule a task to run immediately Source: https://www.nodecron.com/usage-rules.html Use `cron.schedule` when you want the task to start executing immediately according to the cron expression. ```javascript cron.schedule('*/5 * * * *', () => { console.log('running a task every 5 minutes'); }); ``` -------------------------------- ### Configure Global Redis Coordinator with ioredis Source: https://www.nodecron.com/distributed-coordination.html Configure a global Redis run coordinator using ioredis. This setup is similar to node-redis, passing your existing ioredis client. ```javascript import Redis from 'ioredis'; setRunCoordinator(new RedisLockCoordinator(new Redis())); ``` -------------------------------- ### Schedule Task (ESM) Source: https://www.nodecron.com/getting-started.html Schedule a task to run every minute using ESM syntax. This example demonstrates the basic usage of cron.schedule. ```javascript import cron from 'node-cron'; cron.schedule('* * * * *', () => { console.log('Running a task every minute'); }); ``` -------------------------------- ### createTask(expression, func, options?) Source: https://www.nodecron.com/api-reference.html Same as schedule, but does not start the task; it's returned in the stopped state. Useful for attaching event listeners or controlling timing. ```APIDOC ## `createTask(expression, func, options?)` ### Description Same as `schedule`, but **does not start** the task; it's returned in the `stopped` state. Useful when you need to attach event listeners first, start conditionally, or control timing in tests. ### Returns A `ScheduledTask` in the stopped state. ```javascript import cron from 'node-cron'; const task = cron.createTask('0 * * * *', () => { console.log('Running every hour'); }); task.start(); ``` ``` -------------------------------- ### Subscribe to Various Task Lifecycle Events Source: https://www.nodecron.com/event-listening.html Demonstrates subscribing to 'execution:finished', 'task:started', and 'execution:failed' events using .on() and .once(). Shows how to detach listeners with .off(). ```javascript import cron from 'node-cron'; const task = cron.createTask('* * * * *', async (ctx) => { console.log('running at', ctx.dateLocalIso); return 'done'; }); // React every time task.on('execution:finished', (ctx) => { console.log('result:', ctx.execution?.result); }); // React just once, then auto-remove task.once('task:started', () => console.log('scheduler is up')); // Stop listening const onFail = (ctx) => console.error(ctx.execution?.error); task.on('execution:failed', onFail); task.off('execution:failed', onFail); task.start(); ``` -------------------------------- ### Schedule Task (CommonJS) Source: https://www.nodecron.com/getting-started.html Schedule a task to run every minute using CommonJS syntax. This example demonstrates the basic usage of cron.schedule. ```javascript const cron = require('node-cron'); cron.schedule('* * * * *', () => { console.log('Running a task every minute'); }); ``` -------------------------------- ### Schedule and control a cron task Source: https://www.nodecron.com/api-reference.html Schedule a task to run every minute and demonstrate how to stop, start, and destroy the task. ```javascript import cron from 'node-cron'; const task = cron.schedule('* * * * *', () => { console.log('Running every minute'); }); task.stop(); // pause the task task.start(); // start or resume it task.destroy(); // remove it permanently ``` -------------------------------- ### Task State Transitions Source: https://www.nodecron.com/task-lifecycle.html Tasks transition through four states: stopped, idle, running, and destroyed. The start(), stop(), and destroy() methods drive these transitions. ```APIDOC ## Task State Transitions ### Description Illustrates the possible states a task can be in and how methods like `start()`, `stop()`, and `destroy()` affect these states. ### States - `stopped`: Scheduler is not running; task will not fire. - `idle`: Scheduler is running and waiting for the next match. - `running`: The task function is currently executing. - `destroyed`: The task is permanently removed and cannot be restarted. ### Transitions - `stopped` --`start()`--> `idle` - `idle` --`(match fires)`--> `running` - `running` --`(execution ends)`--> `idle` - `idle` --`stop()`--> `stopped` - `running` --`stop()`--> `stopped` - `any state` --`destroy()`--> `destroyed` (terminal) ``` -------------------------------- ### Advanced Task Scheduling with Options Source: https://www.nodecron.com/ Schedule a task with specific options like name, timezone, overlap prevention, and distributed execution. This example also shows how to handle task execution failures. ```javascript import cron from 'node-cron'; const task = cron.schedule('0 3 * * *', './tasks/nightly-backup.js', { name: 'nightly-backup', timezone: 'America/Sao_Paulo', noOverlap: true, distributed: true, }); task.on('execution:failed', (ctx) => { console.error('backup failed:', ctx.execution?.error); }); ``` -------------------------------- ### Control Scheduled Task Source: https://www.nodecron.com/getting-started.html Demonstrates how to control a scheduled task using its returned object. You can stop, start, or destroy the task. ```javascript import cron from 'node-cron'; const task = cron.schedule('* * * * *', () => { console.log('tick'); }); task.stop(); // pause it task.start(); // resume it task.destroy(); // remove it for good ``` -------------------------------- ### Manual Execution of a Background Task Source: https://www.nodecron.com/background-tasks.html Manually execute a background task using the `execute()` method. The task must be started first. This method is asynchronous. ```javascript import cron from 'node-cron'; const task = cron.schedule('0 3 * * *', './tasks/backup.js'); const result = await task.execute(); ``` -------------------------------- ### Designated Runner Setup (Env-Var) Source: https://www.nodecron.com/run-cron-jobs-across-multiple-servers.html Designate a single instance as the runner using an environment variable (`NODE_CRON_RUN`). Other instances should have this variable set to `false` or unset. This is suitable for orchestrators that can designate a specific pod. ```bash # instance A (the runner) NODE_CRON_RUN=true node app.js # instances B, C, D NODE_CRON_RUN=false node app.js ``` -------------------------------- ### Import ScheduleModule in AppModule Source: https://www.nodecron.com/nestjs.html Import ScheduleModule.forRoot() in your main application module to enable scheduling. This setup is identical to using @nestjs/schedule. ```typescript // app.module.ts import { Module } from '@nestjs/common'; import { ScheduleModule } from '@node-cron/nestjs'; import { TasksService } from './tasks.service'; @Module({ imports: [ScheduleModule.forRoot()], providers: [TasksService], }) export class AppModule {} ``` -------------------------------- ### Schedule a cron job with node-cron Source: https://www.nodecron.com/migrating-from-cron.html Use `cron.schedule` to define and start a cron task immediately. Specify the cron expression, the callback function, and an options object for timezone or other settings. ```javascript import cron from 'node-cron'; const task = cron.schedule('0 */5 * * * *', () => doWork(), { timezone: 'America/Sao_Paulo', }); ``` -------------------------------- ### Run Task at Specific Minutes Source: https://www.nodecron.com/cron-syntax.html Use comma-separated values in the minute field to schedule a task at multiple specific minutes within an hour. This example runs at minutes 1, 2, 4, and 5. ```javascript import cron from 'node-cron'; // Runs at minutes 1, 2, 4, and 5 of every hour cron.schedule('1,2,4,5 * * * *', () => { console.log('Running at minutes 1, 2, 4, and 5 of each hour'); }); ``` -------------------------------- ### CronJob constructor with cron package Source: https://www.nodecron.com/migrating-from-cron.html This is the traditional way to create a cron job using the `cron` package, utilizing a constructor with positional arguments for time, tick, completion callback, start status, and timezone. ```javascript const { CronJob } = require('cron'); const job = new CronJob( '0 */5 * * * *', // cronTime () => doWork(), // onTick null, // onComplete true, // start 'America/Sao_Paulo' // timeZone ); ``` -------------------------------- ### Register Fastify Node Cron Plugin Source: https://www.nodecron.com/fastify.html Configure the Fastify Node Cron plugin during application setup. Options include defining initial tasks, providing a run coordinator, custom logger, and controlling auto-start behavior. ```typescript await app.register(fastifyNodeCron, { tasks: [ /* FastifyNodeCronTaskDefinition[] */ ], runCoordinator, logger, autoStart: true, }); ``` -------------------------------- ### v3 Task Event Handling ('task-done') Source: https://www.nodecron.com/migrating-from-v3.html In v3, the `ScheduledTask` extended `EventEmitter` and emitted a `task-done` event after each execution. This example shows how to listen for this event to log the result of a task run. ```javascript const task = cron.schedule('* * * * *', async () => { console.log('Running every minute'); }); task.on('task-done', (result) => { console.log('Run finished:', result); }); ``` -------------------------------- ### Scheduling background tasks with noOverlap Source: https://www.nodecron.com/prevent-overlapping-cron-jobs.html Combine `noOverlap: true` with background tasks (forked processes) to ensure that even if the background task is long-running, new instances are not started until the previous one finishes. ```javascript cron.schedule('*/5 * * * *', './tasks/heavy-sync.js', { noOverlap: true, }); ``` -------------------------------- ### Basic node-cron schedule with noOverlap Source: https://www.nodecron.com/prevent-overlapping-cron-jobs.html Use `noOverlap: true` to prevent a cron job from starting if a previous instance is still running. This ensures only one instance of the job executes at a time. ```javascript import cron from 'node-cron'; cron.schedule('* * * * *', async () => { await longRunningJob(); }, { noOverlap: true, }); ``` -------------------------------- ### Listen to Task Execution Events Source: https://www.nodecron.com/event-listening.html Attach listeners for 'execution:finished' and 'execution:failed' events to log task outcomes. Ensure listeners are attached before the task starts to capture all events. ```javascript import cron from 'node-cron'; const task = cron.schedule('* * * * *', async () => { return doWork(); }); task.on('execution:finished', (ctx) => { console.log(`done in ${ctx.execution?.finishedAt - ctx.execution?.startedAt}ms`); }); task.on('execution:failed', (ctx) => { console.error('failed:', ctx.execution?.error?.message); }); ``` -------------------------------- ### Run Task within a Minute Range Source: https://www.nodecron.com/cron-syntax.html Use a dash (-) to define an inclusive range for a cron field, specifying a continuous interval. This example runs every minute from minute 1 to minute 5. ```javascript import cron from 'node-cron'; // Runs every minute from minute 1 to minute 5 (inclusive) of every hour cron.schedule('1-5 * * * *', () => { console.log('Running every minute from 1 to 5'); }); ``` -------------------------------- ### Basic Cron Schedule with Options Source: https://www.nodecron.com/scheduling-options.html Demonstrates the basic syntax for scheduling a task with optional configuration parameters. This is the entry point for customizing job behavior. ```javascript cron.schedule(expression, task, options); ``` -------------------------------- ### Migrate from @fastify/schedule to @node-cron/fastify Source: https://www.nodecron.com/fastify.html Demonstrates the migration from using toad-scheduler with @fastify/schedule to the simpler cron expression-based scheduling with @node-cron/fastify. ```typescript // Before — @fastify/schedule + toad-scheduler import { fastifySchedule } from '@fastify/schedule'; import { AsyncTask, SimpleIntervalJob } from 'toad-scheduler'; await app.register(fastifySchedule); const task = new AsyncTask('poll', () => pollForData()); app.scheduler.addSimpleIntervalJob(new SimpleIntervalJob({ minutes: 5 }, task)); ``` ```typescript // After — @node-cron/fastify import { fastifyNodeCron } from '@node-cron/fastify'; await app.register(fastifyNodeCron); app.scheduler.schedule('*/5 * * * *', () => pollForData(), { name: 'poll' }); ``` -------------------------------- ### Get Cron Pattern Source: https://www.nodecron.com/task-lifecycle.html Retrieve the original cron expression used to create the task. ```javascript const task = cron.schedule('0 0 12 * * *', () => {}); task.getPattern(); // '0 0 12 * * *' ``` -------------------------------- ### Setting a Global Logger with CommonJS Source: https://www.nodecron.com/logging.html Demonstrates how to set a custom global logger using the CommonJS module system. ```javascript const cron = require('node-cron'); cron.setLogger({ /* ... */ }); ``` -------------------------------- ### Configure Global Redis Coordinator with Node-Redis Source: https://www.nodecron.com/distributed-coordination.html Set up a global Redis-based run coordinator using node-redis. This ensures only one instance runs a scheduled task, and it survives node failures. ```javascript import { createClient } from 'redis'; import cron, { setRunCoordinator } from 'node-cron'; import { RedisLockCoordinator } from '@node-cron/redis-coordinator'; const redis = createClient(); // your client, your connection await redis.connect(); setRunCoordinator(new RedisLockCoordinator(redis)); // Deploy on N instances: only one runs each 3am fire, and it survives the loss of any node. cron.schedule('0 3 * * *', runNightlyBackup, { name: 'nightly-backup', distributed: true, distributedLease: 5 * 60_000, // the backup can take up to ~5 minutes }); ``` -------------------------------- ### Configure Distributed Task with Lease Source: https://www.nodecron.com/distributed-coordination.html Schedule a distributed task with a specified lease time to ensure safety during potential instance crashes. The lease duration must exceed the task's maximum runtime plus any random delay. ```javascript cron.schedule('0 3 * * *', runNightlyBackup, { name: 'nightly-backup', distributed: true, distributedLease: 5 * 60_000, // the backup can take up to ~5 minutes }); ``` -------------------------------- ### Combining Distributed Coordination with Background Tasks Source: https://www.nodecron.com/run-cron-jobs-across-multiple-servers.html Schedule a task to run as a background job using `distributed: true`. The parent process handles coordination, and the forked daemon communicates over IPC to execute the task, requiring no extra configuration for the coordinator. ```javascript setRunCoordinator(new RedisLockCoordinator(redis)); cron.schedule('0 3 * * *', './tasks/backup.js', { name: 'nightly-backup', distributed: true, }); ``` -------------------------------- ### Controlling Background Tasks Asynchronously Source: https://www.nodecron.com/background-tasks.html Control methods for background tasks (stop, start, destroy) are asynchronous and return Promises. `getStatus` remains synchronous. ```javascript import cron from 'node-cron'; const task = cron.schedule('*/5 * * * * *', './tasks/my-task.js'); await task.stop(); // terminates the child process await task.start(); // re-forks and resumes await task.destroy(); // kills the process and removes the task task.getStatus(); // synchronous: 'idle', 'running', etc. ``` -------------------------------- ### Integrating Pino Logger Globally Source: https://www.nodecron.com/logging.html Shows how to integrate the Pino logging library as the global logger for node-cron. Note the handling of the error parameter in the error method. ```javascript import pino from 'pino'; import { setLogger } from 'node-cron'; const log = pino(); setLogger({ info: (m) => log.info(m), warn: (m) => log.warn(m), error: (m, e) => log.error(e ?? m), debug: (m) => log.debug(m), }); ``` -------------------------------- ### Get Remaining Runs Source: https://www.nodecron.com/task-lifecycle.html If `maxExecutions` is configured for a task, `runsLeft()` returns the number of executions remaining before the task automatically destroys itself. Otherwise, it returns `undefined`. ```javascript const task = cron.schedule('* * * * * *', () => {}, { maxExecutions: 3 }); task.runsLeft(); // 3, then 2, 1, 0 ``` -------------------------------- ### setRunCoordinator(coordinator) Source: https://www.nodecron.com/api-reference.html Sets the process-wide run coordinator for tasks scheduled with `distributed: true`. This enables a high-availability setup where only one instance can execute a task. ```APIDOC ## `setRunCoordinator(coordinator)` ### Description Sets the process-wide run coordinator used by tasks scheduled with `distributed: true`. This is the high-availability path: any instance can run a fire, only one wins. Without it, `distributed` tasks fall back to the `NODE_CRON_RUN` env-var default (a single designated runner). ### Parameters #### Path Parameters None #### Query Parameters None #### Request Body * **coordinator** (object | undefined) - Optional - An object implementing the `RunCoordinator` interface, or `undefined` to clear the coordinator. ### Interface Definition ```typescript interface RunCoordinator { shouldRun(key: string, ttlMs: number): boolean | Promise; onComplete?(key: string): void | Promise; } ``` ### Request Example ```javascript import { setRunCoordinator } from 'node-cron'; import { RedisLockCoordinator } from '@node-cron/redis-coordinator'; setRunCoordinator(new RedisLockCoordinator(redis)); ``` ### Response None ### Errors Errors are routed to the logger. ``` -------------------------------- ### Preventing Overlapping Background Tasks Source: https://www.nodecron.com/run-background-jobs-in-nodejs.html Configure a background task with `noOverlap: true` to ensure that a new instance of the task does not start if a previous one is still running. ```javascript cron.schedule('*/5 * * * *', './tasks/sync.js', { noOverlap: true, }); ``` -------------------------------- ### Milliseconds Until Next Run Source: https://www.nodecron.com/task-lifecycle.html Use `msToNext()` to get the number of milliseconds from the current time until the next scheduled task execution. It returns `null` if the task is stopped. ```javascript const task = cron.schedule('0 * * * *', () => {}); task.msToNext(); // e.g. 1830000 ``` -------------------------------- ### Get All Registered Tasks Source: https://www.nodecron.com/api-reference.html Use `getTasks` to retrieve a map of all currently scheduled tasks, keyed by their unique IDs. This is useful for monitoring or managing active tasks. ```javascript import cron from 'node-cron'; const task = cron.schedule('* * * * *', () => { console.log('Running every minute'); }); const tasks = cron.getTasks(); console.log(tasks.has(task.id)); // true console.log(tasks.get(task.id) === task); // true ``` ```javascript import cron from 'node-cron'; for (const [id, task] of cron.getTasks()) { console.log(id, task.name, task.getStatus()); } ``` -------------------------------- ### Scheduled Task Lifecycle Events Source: https://www.nodecron.com/fastify.html Handle lifecycle events for scheduled tasks, such as execution start and failure. The `task.on()` method allows attaching listeners for various events. ```typescript const task = app.scheduler.schedule('* * * * *', () => work(), { name: 'work' }); task.on('execution:started', () => app.log.info('work started')); task.on('execution:failed', (ctx) => app.log.error(ctx.execution?.error)); task.getNextRun(); // Date | null ``` -------------------------------- ### v3 background tasks Source: https://www.nodecron.com/migrating-from-v2.html v3 supports running tasks in a separate forked process by providing a file path string instead of a function. This feature is new in v3. ```javascript // v3 only: runs ./tasks/job.js in a forked process cron.schedule('0 0 * * *', './tasks/job.js', { timezone: 'America/Sao_Paulo' }); ``` -------------------------------- ### Schedule Task in Unref'd State Source: https://www.nodecron.com/task-lifecycle.html Schedule a task to start in an unreferenced state, meaning it won't keep the process alive by itself. This is an alternative to calling task.unref() separately. ```javascript import cron from 'node-cron'; const task = cron.schedule('* * * * * *', () => heartbeat(), { unref: true }); ``` -------------------------------- ### Import node-cron functions Source: https://www.nodecron.com/api-reference.html Import all available functions from the node-cron module for use in your project. ```javascript import cron, { schedule, createTask, validate, validateDetailed, parse, getTasks, getTask, setLogger, setRunCoordinator, shutdown, } from 'node-cron'; ``` -------------------------------- ### Stagger tasks with random delay Source: https://www.nodecron.com/usage-rules.html Employ `maxRandomDelay` to introduce a random delay before the first execution of a task. This helps to stagger the firing of many tasks that are scheduled to start at the same time. ```javascript cron.schedule('* * * * *', () => { console.log('Task executed with a random delay'); }, { maxRandomDelay: 60000 // Max delay of 60 seconds }); ``` -------------------------------- ### Fastify Plugin for Scheduled Jobs Source: https://www.nodecron.com/cookbook.html Integrates node-cron as a Fastify plugin, allowing jobs to be declared during registration and scheduled imperatively from routes. Jobs start on 'onReady' and stop on 'onClose'. ```typescript import Fastify from 'fastify'; import { fastifyNodeCron } from '@node-cron/fastify'; const app = Fastify(); await app.register(fastifyNodeCron, { tasks: [ { cron: '0 3 * * *', name: 'nightly-backup', run: () => runBackup() }, ], }); // schedule on demand, and inspect via the decorator app.post('/reports/enable', async () => { app.scheduler.schedule('*/5 * * * *', () => sendReport(), { name: 'report' }); return { nextRun: app.scheduler.getTaskByName('report')?.getNextRun() }; }); await app.listen({ port: 3000 }); ``` -------------------------------- ### Configuring Distributed Coordination for Background Tasks Source: https://www.nodecron.com/run-background-jobs-in-nodejs.html Enable distributed coordination for background tasks by setting a run coordinator and marking the task as distributed. This is useful for coordinating jobs across multiple instances. ```javascript import { setRunCoordinator } from 'node-cron'; import { RedisLockCoordinator } from '@node-cron/redis-coordinator'; setRunCoordinator(new RedisLockCoordinator(redis)); cron.schedule('0 3 * * *', './tasks/backup.js', { name: 'nightly-backup', distributed: true, }); ``` -------------------------------- ### Get Last Run Information Source: https://www.nodecron.com/task-lifecycle.html Obtain details about the last task execution. Returns null if the task has never run. The 'date' property indicates the finish time of the execution. ```javascript const task = cron.schedule('* * * * *', async () => { return fetchData(); }); // Before any execution task.lastRun(); // null // After a successful run task.lastRun(); // { date: Date, result: ... } // After a failed run task.lastRun(); // { date: Date, error: Error } ``` -------------------------------- ### Schedule a job using plain English Source: https://www.nodecron.com/blog/plain-english-to-cron.html Use `toCron` to convert an English schedule into a cron expression that can be passed to `cron.schedule`. ```javascript import cron from 'node-cron'; import { toCron } from 'cron-translate'; cron.schedule(toCron('every weekday at 6pm'), () => { runDailyReport(); }); ``` -------------------------------- ### Get Task Status Source: https://www.nodecron.com/task-lifecycle.html The `getStatus()` method returns the current state of the task as a string ('stopped', 'idle', 'running', or 'destroyed'). This method is synchronous and works for both inline and background tasks. ```javascript import cron from 'node-cron'; const task = cron.schedule('* * * * *', () => {}); console.log(task.getStatus()); // 'idle' ``` -------------------------------- ### Inline vs. Background Task Execution Source: https://www.nodecron.com/task-lifecycle.html Demonstrates how to schedule tasks inline (synchronously) and in the background (asynchronously) using node-cron. For background tasks, `await` is used with control methods like `stop()`. ```javascript import cron from 'node-cron'; // Inline: synchronous const task = cron.schedule('* * * * *', () => {}); task.getStatus(); // 'idle' task.stop(); task.getStatus(); // 'stopped' // Background: asynchronous const bg = cron.schedule('* * * * *', './tasks/job.js'); await bg.stop(); // wait for the forked process to terminate bg.getStatus(); // 'stopped' ``` -------------------------------- ### Scheduling a Background Task by Path Source: https://www.nodecron.com/background-tasks.html Schedule a background task by providing the file path to the `cron.schedule` function. Relative paths are resolved from the calling file. ```javascript import cron from 'node-cron'; const task = cron.schedule('*/5 * * * * *', './tasks/my-task.js'); ``` -------------------------------- ### v2 task methods vs v3 task methods Source: https://www.nodecron.com/migrating-from-v2.html In v3, `task.getStatus()` and `task.destroy()` were removed. Use `task.stop()` instead of `destroy()`. For status tracking, manage state yourself or upgrade to v4. ```javascript // v2 const task = cron.schedule('* * * * *', () => {}); task.getStatus(); // 'scheduled' | 'running' | 'stoped' | 'destroyed' | 'failed' task.destroy(); // v3: these methods no longer exist const task = cron.schedule('* * * * *', () => {}); task.stop(); // use stop() instead of destroy() ``` -------------------------------- ### Schedule a Cron Job with node-cron Source: https://www.nodecron.com/cron-tester.html Integrate a validated cron expression into your node-cron project to schedule recurring tasks. This example shows how to schedule a function to run daily at 9 AM on weekdays. ```javascript import cron from 'node-cron'; cron.schedule('0 0 9 * * 1-5', () => { runDailyReport(); }); ``` -------------------------------- ### Run Task at Periodic Intervals (Steps) Source: https://www.nodecron.com/cron-syntax.html Use a slash (/) after a wildcard or range to define a step interval for a cron field. This allows scheduling tasks at periodic intervals. ```javascript import cron from 'node-cron'; // Every 2 minutes (even minutes: 0, 2, 4, ...) cron.schedule('*/2 * * * *', () => { console.log('Running every 2 minutes (even minutes)'); }); // Every 2 minutes starting from 1 (odd minutes: 1, 3, 5, ...) cron.schedule('1-59/2 * * * *', () => { console.log('Running every 2 minutes starting from 1 (odd minutes)'); }); ``` -------------------------------- ### Fastify Scheduler API Source: https://www.nodecron.com/fastify.html Interact with scheduled tasks using the `fastify.scheduler` decorator. Methods allow scheduling, retrieving, starting, stopping, and closing tasks, as well as accessing the underlying node-cron instance. ```typescript app.scheduler.schedule(expression, run, options?); // -> ScheduledTask app.scheduler.getTask(id); // by node-cron id app.scheduler.getTaskByName(name); // by your name app.scheduler.getTasks(); // Map app.scheduler.start(); // start owned tasks app.scheduler.stop(); // stop owned tasks (keep them) app.scheduler.close(); // destroy owned tasks app.scheduler.cron; // the underlying node-cron instance ``` -------------------------------- ### Enable Distributed Background Tasks Source: https://www.nodecron.com/distributed-coordination.html Configure Node-Cron to use a coordinator in the main process for background tasks. The parent process handles coordination via IPC, ensuring the shared backend arbitrates across the fleet without extra configuration in the daemon. ```javascript // in your main process setRunCoordinator(new RedisLockCoordinator(redis)); cron.schedule('0 3 * * *', './tasks/backup.js', { name: 'nightly-backup', distributed: true, }); ``` -------------------------------- ### Schedule the Nth Weekday of the Month Source: https://www.nodecron.com/cron-syntax.html Use '#' in the day-of-week field to schedule jobs on the nth occurrence of a specific weekday within a month. For example, '1#1' for the first Monday. ```javascript import cron from 'node-cron'; // Runs at 12:00 on the first Monday of every month cron.schedule('0 12 * * 1#1', () => { console.log('First Monday of the month'); }); // Runs at 09:00 on the 3rd Tuesday of every month cron.schedule('0 9 * * 2#3', () => { console.log('Third Tuesday of the month'); }); ``` -------------------------------- ### Schedule Daily Backup Task Source: https://www.nodecron.com/cookbook.html Schedules a daily backup task to run at 3 AM in a specific timezone. Heavy jobs should be run in a background task to avoid blocking the event loop. The `noOverlap` option ensures the task doesn't run concurrently. ```javascript import cron from 'node-cron'; const backup = cron.schedule('0 3 * * *', './tasks/backup.js', { name: 'daily-backup', timezone: 'America/Sao_Paulo', noOverlap: true, }); backup.on('execution:failed', (ctx) => { console.error('backup failed:', ctx.execution?.error?.message); }); ``` ```javascript export async function task() { await dumpDatabase(); await uploadToStorage(); } ``` -------------------------------- ### Schedule Background Task in v4 Source: https://www.nodecron.com/migrating-from-v3.html Schedule a background task by providing a file path. Options like timezone can be passed. Background tasks now implement the same ScheduledTask interface as inline tasks. ```javascript cron.schedule('0 0 * * *', './tasks/daily-backup.js', { timezone: 'America/New_York' }); ``` -------------------------------- ### Import node-cron Source: https://www.nodecron.com/migrating-from-v2.html The import method remains the same for both v2 and v3 as they are CommonJS modules. ```javascript const cron = require('node-cron'); ``` -------------------------------- ### execute() Source: https://www.nodecron.com/task-lifecycle.html Runs the task function immediately, outside its schedule. It always returns a Promise and is useful for testing, debugging, or ad-hoc runs. It resolves with the task's return value or rejects if it throws, emitting the same lifecycle events as a scheduled run. ```APIDOC ## execute() ### Description Runs the task function immediately, outside its schedule. This method is useful for testing, debugging, or ad-hoc runs. It always returns a `Promise` that resolves with the task's return value or rejects if the task throws an error. It emits the same lifecycle events as a scheduled run, with `execution.reason` set to `'invoked'`. ### Method `execute()` ### Parameters None ### Request Example ```javascript import cron from 'node-cron'; const task = cron.schedule('0 3 * * *', async () => { return doBackup(); }); // Trigger a run right now without waiting for 03:00 const result = await task.execute(); ``` ### Response #### Success Response - **Return Value** (any) - The return value of the task function. #### Error Response - **Error** - Throws an error if the task function throws an error. ``` -------------------------------- ### Check Clock Skew with Redis Coordinator Source: https://www.nodecron.com/distributed-coordination.html Use `healthCheck()` to compare the local clock to the Redis server clock. Run this at startup or on a health endpoint to detect and alert on clock drift, preventing unreliable distributed coordination. ```javascript const coordinator = new RedisLockCoordinator(redis); cron.setRunCoordinator(coordinator); const { ok, driftMs } = await coordinator.healthCheck(); // default threshold 1000ms if (!ok) { console.warn(`clock skew vs Redis is ${driftMs}ms; distributed coordination may be unreliable`); } ```