@nestjs/schedule

repository·master·Indexed 19 days ago

https://github.com/nestjs/schedule

A NestJS module providing task scheduling capabilities powered by node-cron. It allows developers to execute tasks using the @Cron, @Interval, and @Timeout decorators, or programmatically via the SchedulerRegistry. Features include support for cron expressions, predefined CronExpression enums, and configurable options for timezones, delays, and concurrency control.

Tokens
5K
Snippets
25
Records
28
Agent score
65%

What's inside @nestjs/schedule

  1. Overview of NestJS Task Scheduling

    master
    The @nestjs/schedule module provides task scheduling capabilities for NestJS applications, built on top of the node-cron package. It allows you to execute tasks at specific intervals or using cron expressions.
  2. Configure ScheduleModuleOptions

    master

    When initializing the ScheduleModule, you can provide a ScheduleModuleOptions object to control which types of scheduled tasks are enabled.

    Available options:

    • cronJobs: Boolean flag to enable or disable Cron jobs.
    • intervals: Boolean flag to enable or disable Intervals.
    • timeouts: Boolean flag to enable or disable Timeouts.
    const options: ScheduleModuleOptions = {
      cronJobs: true,
      intervals: true,
      timeouts: true,
    };
  3. Use the @Timeout decorator to schedule tasks after a delay

    master

    The @Timeout decorator is used to schedule a method to execute once after a specific delay, behaving like a standard setTimeout.

    You can provide the delay in milliseconds, and optionally provide a unique name for the timeout task.

    Overloads:

    • @Timeout(timeout: number): Schedules a task with the specified delay.
    • @Timeout(name: string, timeout: number): Schedules a named task with the specified delay.
    import { Timeout } from '@nestjs/schedule';
    
    class MyService {
      @Timeout(5000)
      handleTimeout() {
        // This runs once after 5 seconds
      }
    
      @Timeout('my-custom-task', 10000)
      handleNamedTimeout() {
        // This runs once after 10 seconds and is identified by 'my-custom-task'
      }
    }
  4. Register a CronJob using SchedulerRegistry.addCronJob()

    master

    Manually add a CronJob instance to the registry. When a job is added via this method, the registry automatically wraps the job's fireOnTick method in a try-catch block to ensure that errors within the job do not crash the scheduler and are logged instead.

    Parameters:

    • name: A unique string identifier for the job.
    • job: The CronJob instance to register.

    Throws:

    • Throws an error if a job with the same name is already registered (using the DUPLICATE_SCHEDULER error message).
    import { CronJob } from 'cron';
    
    const job = new CronJob('*/5 * * * *', () => console.log('Running...'));
    schedulerRegistry.addCronJob('my-cron-job', job);
  5. Delete a scheduled task from the registry

    master

    Use the following methods to stop and remove tasks from the registry:

    • deleteCronJob(name): Stops the specified CronJob and removes it from the registry.
    • deleteInterval(name): Clears the specified interval using clearInterval and removes it from the registry.
    • deleteTimeout(name): Clears the specified timeout using clearTimeout and removes it from the registry.

    Note: All delete methods will throw an error if the task name does not exist, as they rely on the get... methods which validate existence.

    schedulerRegistry.deleteCronJob('my-cron-job');
    schedulerRegistry.deleteInterval('my-interval');
    schedulerRegistry.deleteTimeout('my-timeout');
  6. Use scheduling decorators

    master
    The library exports various decorators (such as @Cron, @Interval, and @Timeout) used to define scheduled tasks directly on class methods. These decorators require ScheduleModule to be initialized in the application.
  7. Use ScheduleModule to enable task scheduling

    master

    To use the scheduling features in your NestJS application, you must import and register the ScheduleModule. This module provides the necessary infrastructure for decorators like @Cron to function.

    import { Module } from '@nestjs/common';
    import { ScheduleModule } from '@nestjs/schedule';
    
    @Module({
      imports: [
        ScheduleModule.forRoot(),
      ],
    })
    export class AppModule {}
  8. Access scheduled jobs via SchedulerRegistry

    master

    The ScheduleModule exports the SchedulerRegistry class. You can inject SchedulerRegistry into your services to programmatically access, stop, or manage the cron jobs, intervals, and timeouts registered within the application.

    import { Injectable } from '@nestjs/common';
    import { SchedulerRegistry } from '@nestjs/schedule';
    
    @Injectable()
    export class MyService {
      constructor(private schedulerRegistry: SchedulerRegistry) {}
    
      // Use schedulerRegistry to manage jobs
    }
  9. Retrieve a registered Timeout using SchedulerRegistry.getTimeout()

    master

    Retrieve the identifier for a registered timeout task.

    Throws:

    • Throws an error if no timeout is found with the provided name (using the NO_SCHEDULER_FOUND error message).

    Returns:

    • The timeout identifier (e.g., the value returned by setTimeout).
    const timeoutId = schedulerRegistry.getTimeout('my-timeout');
  10. Register a Timeout using SchedulerRegistry.addTimeout()

    master

    Manually add a timeout identifier to the registry.

    Parameters:

    • name: A unique string identifier for the timeout.
    • timeoutId: The identifier returned by setTimeout.

    Throws:

    • Throws an error if a timeout with the same name is already registered (using the DUPLICATE_SCHEDULER error message).
    const timeoutId = setTimeout(() => { /* logic */ }, 5000);
    schedulerRegistry.addTimeout('my-timeout', timeoutId);
  11. List all registered CronJobs, Intervals, or Timeouts

    master

    The SchedulerRegistry provides methods to inspect all currently managed tasks:

    • getCronJobs(): Returns a Map<string, CronJob> containing all registered cron jobs.
    • getIntervals(): Returns a string[] containing the names of all registered intervals.
    • getTimeouts(): Returns a string[] containing the names of all registered timeouts.
    const allCronJobs = schedulerRegistry.getCronJobs();
    const intervalNames = schedulerRegistry.getIntervals();
    const timeoutNames = schedulerRegistry.getTimeouts();