### Install @nestjs/schedule Source: https://github.com/nestjs/schedule/blob/master/_autodocs/quick-start.md Install the @nestjs/schedule package using npm. ```bash npm install @nestjs/schedule ``` -------------------------------- ### CronOptions Example Source: https://github.com/nestjs/schedule/blob/master/_autodocs/types.md Example of configuring cron job options, including name, timeZone, and initialDelay. ```typescript const cronOptions: CronOptions = { name: 'daily-task', timeZone: 'America/New_York', waitForCompletion: true, initialDelay: 5000, }; ``` -------------------------------- ### Run NestJS Application Source: https://github.com/nestjs/schedule/blob/master/_autodocs/quick-start.md Start your NestJS application using the npm start command. ```bash npm run start ``` -------------------------------- ### ScheduleModule Initialization - Enable All Schedulers Source: https://github.com/nestjs/schedule/blob/master/_autodocs/schedule-module.md Use ScheduleModule.forRoot() to import the module and enable all schedulers (cron jobs, intervals, timeouts) by default. This is the simplest way to get started with task scheduling. ```typescript import { Module } from '@nestjs/common'; import { ScheduleModule } from '@nestjs/schedule'; @Module({ imports: [ScheduleModule.forRoot()], }) export class AppModule {} ``` -------------------------------- ### Configuration Source: https://github.com/nestjs/schedule/blob/master/_autodocs/README.md Details on configuring the NestJS Schedule module, including synchronous and asynchronous setup options, different async patterns, environment variable examples, and conditional configuration. ```APIDOC ## Configuration ### Synchronous Setup (`forRoot`) **Description:** Configure the ScheduleModule synchronously. **Usage:** ```typescript @Module({ imports: [ ScheduleModule.forRoot({ enable: true }) ] }) export class AppModule {} ``` **Options:** - `enable` (boolean) - Whether to enable the schedule module. ### Asynchronous Setup (`forRootAsync`) **Description:** Configure the ScheduleModule asynchronously. **Usage Patterns:** 1. **`useFactory`:** ```typescript @Module({ imports: [ ScheduleModule.forRootAsync({ imports: [ConfigModule], useFactory: async (configService: ConfigService) => ({ enable: configService.get('SCHEDULE_ENABLE') }), inject: [ConfigService], }) ] }) export class AppModule {} ``` 2. **`useClass`:** ```typescript @Module({ imports: [ ScheduleModule.forRootAsync({ useClass: ScheduleConfigService }) ] }) export class AppModule {} @Injectable() class ScheduleConfigService implements ScheduleModuleOptionsFactory { createScheduleOptions(): ScheduleModuleOptions { return { enable: true }; } } ``` 3. **`useExisting`:** ```typescript @Module({ imports: [ ScheduleModule.forRootAsync({ imports: [ConfigModule], useExisting: ScheduleConfigService }) ] }) export class AppModule {} ``` **Environment Variable Examples:** - `SCHEDULE_ENABLE=true` **Conditional Configuration:** Configuration can be made conditional based on environment variables or other dynamic factors using the `useFactory` or custom factory services. ``` -------------------------------- ### onApplicationBootstrap() Lifecycle Hook Source: https://github.com/nestjs/schedule/blob/master/_autodocs/scheduler-orchestrator.md This method is called when the application starts. It mounts all discovered schedulers, including timeouts, intervals, and cron jobs, registering them with the SchedulerRegistry and starting them as configured. ```typescript onApplicationBootstrap(): void ``` -------------------------------- ### Recommended Environment Variables for Schedule Module Source: https://github.com/nestjs/schedule/blob/master/_autodocs/configuration.md Example .env file content for enabling/disabling schedule features. ```bash # .env file ENABLE_CRON=true ENABLE_INTERVALS=true ENABLE_TIMEOUTS=true ``` -------------------------------- ### Example ScheduleModuleOptions Configuration Source: https://github.com/nestjs/schedule/blob/master/_autodocs/types.md An example of how to configure ScheduleModuleOptions. This configuration enables cron jobs and timeouts while disabling intervals. ```typescript const options: ScheduleModuleOptions = { cronJobs: true, intervals: false, timeouts: true, }; ``` -------------------------------- ### ScheduleModule Async Options Factory Example Source: https://github.com/nestjs/schedule/blob/master/_autodocs/types.md Example of providing asynchronous options for ScheduleModule using a factory function and injecting ConfigService. ```typescript const asyncOptions: ScheduleModuleAsyncOptions = { useFactory: (configService: ConfigService) => ({ cronJobs: configService.get('ENABLE_CRON'), intervals: true, timeouts: true, }), inject: [ConfigService], }; ``` -------------------------------- ### Complete Scheduler Registry Example Source: https://github.com/nestjs/schedule/blob/master/_autodocs/scheduler-registry.md This example demonstrates how to use the SchedulerRegistry to manage cron jobs. It includes methods for generating reports, pausing, resuming, adding, removing, and listing jobs. Ensure the `SchedulerRegistry` is injected into your service. ```typescript import { Injectable } from '@nestjs/common'; import { Cron, CronExpression, SchedulerRegistry } from '@nestjs/schedule'; import { CronJob } from 'cron'; @Injectable() export class TasksService { constructor(private schedulerRegistry: SchedulerRegistry) {} @Cron(CronExpression.EVERY_DAY_AT_MIDNIGHT, { name: 'daily-report', }) generateDailyReport() { console.log('Generating daily report...'); } pauseJob(jobName: string) { const job = this.schedulerRegistry.getCronJob(jobName); if (job) { job.stop(); } } resumeJob(jobName: string) { const job = this.schedulerRegistry.getCronJob(jobName); if (job) { job.start(); } } addDynamicJob(name: string, cronTime: string) { const job = new CronJob(cronTime, () => { console.log(`Dynamic job ${name} executed`); }); this.schedulerRegistry.addCronJob(name, job); job.start(); } removeDynamicJob(name: string) { if (this.schedulerRegistry.doesExist('cron', name)) { this.schedulerRegistry.deleteCronJob(name); } } listAllJobs() { const cronJobs = this.schedulerRegistry.getCronJobs(); const intervals = this.schedulerRegistry.getIntervals(); const timeouts = this.schedulerRegistry.getTimeouts(); console.log('Cron jobs:', Array.from(cronJobs.keys())); console.log('Intervals:', intervals); console.log('Timeouts:', timeouts); } } ``` -------------------------------- ### Synchronous Configuration with Options Source: https://github.com/nestjs/schedule/blob/master/_autodocs/configuration.md Configure the ScheduleModule synchronously by passing options to ScheduleModule.forRoot(). This example enables all schedulers. ```typescript import { Module } from '@nestjs/common'; import { ScheduleModule } from '@nestjs/schedule'; @Module({ imports: [ ScheduleModule.forRoot({ cronJobs: true, intervals: true, timeouts: true, }), ], }) export class AppModule {} ``` -------------------------------- ### Controlling a Cron Job with SchedulerRegistry Source: https://github.com/nestjs/schedule/blob/master/_autodocs/types.md Example demonstrating how to retrieve and control a specific cron job using the SchedulerRegistry. Useful for starting, stopping, and inspecting job status. ```typescript import { SchedulerRegistry } from '@nestjs/schedule'; @Injectable() export class TasksService { constructor(private registry: SchedulerRegistry) {} controlJob(name: string) { const job: CronJob = this.registry.getCronJob(name); if (job.isActive) { job.stop(); // Stop the job } else { job.start(); // Start the job } console.log('Last execution:', job.lastDate()); console.log('Next execution:', job.nextDate()); } } ``` -------------------------------- ### Commit message samples Source: https://github.com/nestjs/schedule/blob/master/CONTRIBUTING.md Examples of valid commit messages following the project conventions. ```text docs(changelog): update change log to beta.5 fix(core): need to depend on latest rxjs and zone.js ``` -------------------------------- ### Startup Initialization With Delay Source: https://github.com/nestjs/schedule/blob/master/_autodocs/quick-start.md Initialize services like database connection and cache warmup after a delay when the application starts. Uses CronExpression.EVERY_5_MINUTES with an initialDelay of 30000 milliseconds. ```typescript import { Injectable, Logger, } from '@nestjs/common'; import { Cron, CronExpression } from '@nestjs/schedule'; @Injectable() export class InitService { constructor(private database: Database, private cache: Cache) {} @Cron(CronExpression.EVERY_5_MINUTES, { name: 'delayed-init', initialDelay: 30000, // Wait 30 seconds after app starts }) async initializeServices() { console.log('Initializing services...'); await this.database.connect(); await this.cache.warmup(); console.log('Services initialized'); } } ``` -------------------------------- ### Example: Complete CronOptions Configuration Source: https://github.com/nestjs/schedule/blob/master/_autodocs/configuration.md Demonstrates how to apply various CronOptions to a @Cron decorator for a daily report generation task. ```typescript @Injectable() export class TasksService { @Cron(CronExpression.EVERY_DAY_AT_MIDNIGHT, { name: 'daily-report-generator', timeZone: 'America/New_York', waitForCompletion: true, threshold: 500, initialDelay: 10000, }) async generateDailyReport() { // Long-running task await this.database.generateReport(); } } ``` -------------------------------- ### ScheduleModule Asynchronous Setup Source: https://github.com/nestjs/schedule/blob/master/_autodocs/overview.md Use ScheduleModule.forRootAsync() for asynchronous initialization of the ScheduleModule, often when configuration depends on other services. ```typescript imports: [ ScheduleModule.forRootAsync(options) ] ``` -------------------------------- ### SchedulerRegistry - Runtime Task Management Source: https://github.com/nestjs/schedule/blob/master/_autodocs/README.md Access and manage scheduled tasks at runtime using the SchedulerRegistry service. This example shows how to get a cron job by its name. ```typescript import { SchedulerRegistry } from '@nestjs/schedule'; import { CronJob } from 'cron'; @Injectable() export class MyService { constructor(private schedulerRegistry: SchedulerRegistry) {} getJob(name: string): CronJob { return this.schedulerRegistry.getCronJob(name); } } ``` -------------------------------- ### Daily Cron Job Examples Source: https://github.com/nestjs/schedule/blob/master/_autodocs/cron-expression.md Illustrates how to schedule daily tasks using specific time-based cron expressions in NestJS. These examples show common daily operations like rollovers and reports. ```typescript @Injectable() export class DailyService { @Cron(CronExpression.EVERY_DAY_AT_MIDNIGHT) dailyRollover() { console.log('Daily reset'); } @Cron(CronExpression.EVERY_DAY_AT_9AM) morningReport() { console.log('Morning report'); } @Cron(CronExpression.EVERY_DAY_AT_6PM) eveningBackup() { console.log('Backup'); } } ``` -------------------------------- ### Example: Minute-level Cron Jobs Source: https://github.com/nestjs/schedule/blob/master/_autodocs/cron-expression.md Demonstrates how to use minute-level CronExpression values with the @Cron() decorator to schedule tasks at hourly or daily intervals. ```typescript @Injectable() export class MaintenanceService { @Cron(CronExpression.EVERY_MINUTE) handleEveryMinute() { console.log('Minute task'); } @Cron(CronExpression.EVERY_10_MINUTES) syncWithRemoteServer() { console.log('Remote sync'); } @Cron(CronExpression.EVERY_30_MINUTES) cleanupTemporaryFiles() { console.log('Cleanup'); } } ``` -------------------------------- ### Implement ScheduleModuleOptionsFactory Source: https://github.com/nestjs/schedule/blob/master/_autodocs/types.md Example implementation of the ScheduleModuleOptionsFactory interface. This service provides schedule module options asynchronously. ```typescript import { Injectable } from '@nestjs/common'; import { ScheduleModuleOptionsFactory, ScheduleModuleOptions } from '@nestjs/schedule'; @Injectable() export class ScheduleConfigService implements ScheduleModuleOptionsFactory { async createScheduleOptions(): Promise { return { cronJobs: true, intervals: true, timeouts: true, }; } } ``` -------------------------------- ### Non-Static Provider Warning Example Source: https://github.com/nestjs/schedule/blob/master/_autodocs/errors.md This example demonstrates a scheduled method defined in a request-scoped service, which triggers a warning. Scheduled methods must be in singleton providers. ```typescript import { Injectable, Scope, } from '@nestjs/common'; import { Cron, CronExpression } from '@nestjs/schedule'; @Injectable({ scope: Scope.REQUEST }) export class RequestScopedService { @Cron(CronExpression.EVERY_HOUR) scheduleTask() { // This won't execute } } // Logs: Cannot register cron job "RequestScopedService@scheduleTask" // because it is defined in a non static provider. ``` -------------------------------- ### Advanced NestJS Schedule Timeout Example Source: https://github.com/nestjs/schedule/blob/master/_autodocs/decorators-timeout.md This advanced example demonstrates multiple @Timeout decorators for tasks like 'warmup-databases' and 'start-background-services'. It also includes methods for dynamically scheduling and canceling tasks using the SchedulerRegistry. ```typescript import { Injectable, Logger } from '@nestjs/common'; import { Timeout, SchedulerRegistry } from '@nestjs/schedule'; @Injectable() export class ApplicationService { private readonly logger = new Logger(ApplicationService.name); constructor(private schedulerRegistry: SchedulerRegistry) {} @Timeout('warmup-databases', 2000) async warmupDatabases() { this.logger.log('Starting database warmup...'); try { // Initialize database connections await this.initializeDatabases(); this.logger.log('Database warmup completed'); } catch (error) { this.logger.error(`Database warmup failed: ${error.message}`); } } @Timeout('start-background-services', 5000) async startBackgroundServices() { this.logger.log('Starting background services...'); // Start workers, processors, etc. } scheduleDynamicTask(name: string, delayMs: number, task: () => void) { const timeout = setTimeout(() => { try { task(); } catch (error) { this.logger.error(`Dynamic task ${name} failed: ${error.message}`); } }, delayMs); this.schedulerRegistry.addTimeout(name, timeout); this.logger.log(`Scheduled task ${name} for execution in ${delayMs}ms`); } cancelScheduledTask(name: string) { if (this.schedulerRegistry.doesExist('timeout', name)) { this.schedulerRegistry.deleteTimeout(name); this.logger.log(`Canceled task ${name}`); } } } ``` -------------------------------- ### Example: Second-level Cron Jobs Source: https://github.com/nestjs/schedule/blob/master/_autodocs/cron-expression.md Demonstrates how to use second-level CronExpression values with the @Cron() decorator to schedule tasks at frequent intervals. ```typescript @Injectable() export class MonitoringService { @Cron(CronExpression.EVERY_SECOND) checkSystemStatus() { console.log('System check'); } @Cron(CronExpression.EVERY_5_SECONDS) pollExternalAPI() { console.log('Polling API'); } } ``` -------------------------------- ### Start and Stop Task Source: https://github.com/nestjs/schedule/blob/master/_autodocs/INDEX.md Control the execution of a scheduled task by calling its start() and stop() methods. These methods are available on the job object obtained from the SchedulerRegistry. ```typescript job.start() ``` ```typescript job.stop() ``` -------------------------------- ### Minimal Cron Job Setup Source: https://github.com/nestjs/schedule/blob/master/_autodocs/INDEX.md Defines a basic cron job that runs every hour. Ensure @nestjs/schedule is imported and the service is provided. ```typescript import { Injectable } from '@nestjs/common'; import { Cron, CronExpression } from '@nestjs/schedule'; @Injectable() export class TasksService { @Cron(CronExpression.EVERY_HOUR) handleTask() { console.log('Task executed'); } } ``` -------------------------------- ### Singleton Provider for Scheduling Source: https://github.com/nestjs/schedule/blob/master/_autodocs/errors.md This example shows the correct way to define a scheduled method using the default singleton scope for a service. This ensures the cron job executes. ```typescript import { Injectable, } from '@nestjs/common'; import { Cron, CronExpression } from '@nestjs/schedule'; @Injectable() // Default scope is singleton export class ScheduledService { @Cron(CronExpression.EVERY_HOUR) scheduleTask() { // This will execute } } ``` -------------------------------- ### Classes: ScheduleModule, SchedulerRegistry Source: https://github.com/nestjs/schedule/blob/master/_autodocs/README.md Documentation for the ScheduleModule and SchedulerRegistry classes, including constructor details, public methods, parameter tables, return types, error conditions, usage examples, and runtime control patterns. ```APIDOC ## Classes ### ScheduleModule **Description:** The main module for scheduling tasks in NestJS. **Usage:** Import this module into your application's root module. **Configuration:** - `forRoot(options?)` - `forRootAsync(options?)` ### SchedulerRegistry **Description:** A registry to manage and control scheduled tasks. **Constructor:** `constructor(private readonly scheduler: SchedulerRegistry)` **Public Methods:** #### `addCronJob(name: string, job: CronJob, options?: CronJobOptions)` **Description:** Adds a new cron job to the registry. **Parameters:** - **name** (string) - Required - The unique name of the cron job. - **job** (CronJob) - Required - The CronJob instance. - **options** (CronJobOptions) - Optional - Options for the cron job. **Return Type:** `void` #### `addInterval(name: string, interval: NodeJS.Timeout, options?: IntervalOptions)` **Description:** Adds a new interval task to the registry. **Parameters:** - **name** (string) - Required - The unique name of the interval. - **interval** (NodeJS.Timeout) - Required - The interval timer. - **options** (IntervalOptions) - Optional - Options for the interval. **Return Type:** `void` #### `addTimeout(name: string, timeout: NodeJS.Timeout, options?: TimeoutOptions)` **Description:** Adds a new timeout task to the registry. **Parameters:** - **name** (string) - Required - The unique name of the timeout. - **timeout** (NodeJS.Timeout) - Required - The timeout timer. - **options** (TimeoutOptions) - Optional - Options for the timeout. **Return Type:** `void` #### `get(name: string): T` **Description:** Retrieves a scheduled task by its name. **Parameters:** - **name** (string) - Required - The name of the task to retrieve. **Return Type:** `T` - The scheduled task. #### `delete(name: string): boolean` **Description:** Deletes a scheduled task by its name. **Parameters:** - **name** (string) - Required - The name of the task to delete. **Return Type:** `boolean` - True if the task was deleted, false otherwise. #### `startAll(): void` **Description:** Starts all scheduled tasks. **Return Type:** `void` #### `stopAll(): void` **Description:** Stops all scheduled tasks. **Return Type:** `void` **Runtime Control Patterns:** - Starting/stopping individual jobs. - Pausing/resuming jobs. **Source File:** `lib/scheduler.registry.ts` ``` -------------------------------- ### Create a new git branch Source: https://github.com/nestjs/schedule/blob/master/CONTRIBUTING.md Use this command to start a new feature or fix branch from the master branch. ```shell git checkout -b my-fix-branch master ``` -------------------------------- ### Decorators: @Cron, @Interval, @Timeout Source: https://github.com/nestjs/schedule/blob/master/_autodocs/README.md Documentation for the @Cron, @Interval, and @Timeout decorators, including their function signatures, parameters, return types, usage examples, advanced options, common use cases, error conditions, and source file locations. ```APIDOC ## Decorators ### @Cron **Signature:** `(cronExpression: string, options?: CronOptions) => MethodDecorator` **Description:** Decorator to schedule a method to run on a cron expression. **Parameters:** - **cronExpression** (string) - Required - The cron string defining when the task should run. - **options** (CronOptions) - Optional - Configuration options for the cron job. **Return Type:** `MethodDecorator` **Examples:** ```typescript @Cron('45 * * * *') handleCron() { this.logger.log('Called when the current second is 45'); } ``` ### @Interval **Signature:** `(milliseconds: number, options?: IntervalOptions) => MethodDecorator` **Description:** Decorator to schedule a method to run at a specified interval. **Parameters:** - **milliseconds** (number) - Required - The interval in milliseconds. - **options** (IntervalOptions) - Optional - Configuration options for the interval. **Return Type:** `MethodDecorator` **Examples:** ```typescript @Interval(1000) // Runs every second handleInterval() { this.logger.log('Called every second'); } ``` ### @Timeout **Signature:** `(milliseconds: number, options?: TimeoutOptions) => MethodDecorator` **Description:** Decorator to schedule a method to run once after a specified delay. **Parameters:** - **milliseconds** (number) - Required - The delay in milliseconds. - **options** (TimeoutOptions) - Optional - Configuration options for the timeout. **Return Type:** `MethodDecorator` **Examples:** ```typescript @Timeout(5000) // Runs after 5 seconds handleTimeout() { this.logger.log('Called once after 5 seconds'); } ``` **Advanced Options:** - `immediate`: If true, the task will run immediately on startup. **Common Use Cases:** - Running background jobs periodically. - Executing tasks after a certain delay. **Error Conditions:** - Invalid cron expression. - Negative milliseconds. **Source File:** `lib/schedule.decorators.ts` ``` -------------------------------- ### Hourly Cron Job Examples Source: https://github.com/nestjs/schedule/blob/master/_autodocs/cron-expression.md Demonstrates how to use hourly cron expressions to schedule methods within a NestJS service. Ensure the @Cron decorator is imported. ```typescript @Injectable() export class BatchJobService { @Cron(CronExpression.EVERY_HOUR) hourlyReport() { console.log('Hourly report'); } @Cron(CronExpression.EVERY_6_HOURS) sixHourlyDatabaseMaintenance() { console.log('Database maintenance'); } @Cron(CronExpression.EVERY_12_HOURS) twiceADay() { console.log('Twice daily task'); } } ``` -------------------------------- ### Application Warmup with @Timeout Source: https://github.com/nestjs/schedule/blob/master/_autodocs/decorators-timeout.md Use @Timeout to warm up the cache when the application starts. The decorated method will execute after the specified delay. ```typescript import { Injectable } from '@nestjs/common'; import { Timeout } from '@nestjs/schedule'; @Injectable() export class CacheService { private cache: Map = new Map(); @Timeout('cache-warmup', 5000) async warmUpCache() { console.log('Warming up cache...'); const data = await this.fetchInitialData(); this.cache.set('initial', data); console.log('Cache warmed up'); } private async fetchInitialData() { // Fetch from database or external service return {}; } } ``` -------------------------------- ### SchedulerRegistry Source: https://github.com/nestjs/schedule/blob/master/_autodocs/README.md The SchedulerRegistry service allows for runtime management of scheduled tasks. You can use it to add, retrieve, delete, start, and stop schedulers. ```APIDOC ## SchedulerRegistry ### Description Service for runtime task access and management. Allows adding, deleting, starting, and stopping schedulers. ### Methods - `addCron(name, cronJob)` - `addInterval(name, interval)` - `addTimeout(name, timeout) - `getCronJob(name)` - `getInterval(name)` - `getTimeout(name)` - `deleteCron(name)` - `deleteInterval(name)` - `deleteTimeout(name)` - `startAll()` - `stopAll()` ### Types - `CronOptions` - `IntervalMetadata` - `TimeoutMetadata` ``` -------------------------------- ### Checking Scheduler Existence Source: https://github.com/nestjs/schedule/blob/master/_autodocs/types.md Example of using the `doesExist` method from the SchedulerRegistry to check if a scheduler with a specific type and name exists. Demonstrates type safety with string literal types. ```typescript const exists = registry.doesExist('cron', 'my-job'); // string literal type const invalid = registry.doesExist('invalid', 'my-job'); // Type error ``` -------------------------------- ### Using @Interval Decorator Source: https://github.com/nestjs/schedule/blob/master/_autodocs/README.md Schedule tasks to repeat at a fixed interval using the @Interval decorator. This example shows a task that runs every 5 seconds. ```typescript import { Interval } from '@nestjs/schedule'; @Injectable() export class MyTaskService { @Interval('myInterval', 5000) // Runs every 5 seconds handleInterval() { console.log('Called every 5 seconds'); } } ``` -------------------------------- ### Complex Interval with SchedulerRegistry Source: https://github.com/nestjs/schedule/blob/master/_autodocs/decorators-interval.md An example of a health check interval that logs system health and demonstrates how to use SchedulerRegistry to check if an interval exists and retrieve all active intervals. ```typescript import { Injectable, Logger } from '@nestjs/common'; import { Interval, SchedulerRegistry } from '@nestjs/schedule'; @Injectable() export class HealthCheckService { private readonly logger = new Logger(HealthCheckService.name); constructor( private schedulerRegistry: SchedulerRegistry, private healthRepository: HealthRepository, ) {} @Interval('health-check', 30000) // Every 30 seconds async checkHealth() { const startTime = Date.now(); try { const status = await this.healthRepository.getSystemHealth(); const duration = Date.now() - startTime; this.logger.log( `Health check completed in ${duration}ms - Status: ${status.healthy}`, ); } catch (error) { this.logger.error(`Health check failed: ${error.message}`); } } getHealthCheckStatus(): boolean { return this.schedulerRegistry.doesExist('interval', 'health-check'); } getAllActiveIntervals(): string[] { return this.schedulerRegistry.getIntervals(); } } ``` -------------------------------- ### Get Non-existent Timeout Source: https://github.com/nestjs/schedule/blob/master/_autodocs/errors.md Shows an example of requesting a timeout that has not been registered, which triggers a NO_SCHEDULER_FOUND error. ```typescript const registry = app.get(SchedulerRegistry); const timeout = registry.getTimeout('missing-timeout'); // Throws: Error: No Timeout was found with the given name (missing-timeout). // Check that you created one with a decorator or with the create API. ``` -------------------------------- ### Retrieve and Control a Cron Job Source: https://github.com/nestjs/schedule/blob/master/_autodocs/scheduler-registry.md Get a specific cron job by its registered name using `getCronJob`. Once retrieved, you can interact with the `CronJob` instance, such as stopping or starting it. ```typescript const job = this.schedulerRegistry.getCronJob('daily-report'); job.stop(); // Stop the job job.start(); // Start the job ``` -------------------------------- ### Add a Cron Job Dynamically Source: https://github.com/nestjs/schedule/blob/master/_autodocs/scheduler-registry.md Register a new cron job at runtime using `addCronJob`. This method requires a unique name for the job and a `CronJob` instance. Ensure the job is started after registration if immediate execution is desired. ```typescript import { CronJob } from 'cron'; import { CronExpression } from '@nestjs/schedule'; const job = new CronJob(CronExpression.EVERY_HOUR, () => { console.log('Hourly task'); }); this.schedulerRegistry.addCronJob('hourly-task', job); job.start(); ``` -------------------------------- ### Implement Batch Processing with NestJS Schedule Source: https://github.com/nestjs/schedule/blob/master/_autodocs/advanced-patterns.md Use `@Cron` to periodically process items in batches. This example demonstrates how to manage a queue of items and process them in chunks, returning failed items to the queue. ```typescript import { Injectable, Logger } from '@nestjs/common'; import { Cron, CronExpression } from '@nestjs/schedule'; @Injectable() export class BatchProcessingService { private readonly logger = new Logger(BatchProcessingService.name); private pendingItems: string[] = []; addItem(item: string) { this.pendingItems.push(item); } @Cron(CronExpression.EVERY_MINUTE, { name: 'batch-processor', }) async processBatch() { if (this.pendingItems.length === 0) { return; } const batchSize = 100; const batch = this.pendingItems.splice(0, batchSize); try { await this.processBatchItems(batch); this.logger.log(`Processed batch of ${batch.length} items`); } catch (error) { // Return items to queue on failure this.pendingItems.unshift(...batch); this.logger.error(`Batch processing failed: ${error.message}`); } } private async processBatchItems(items: string[]) { // Process items } } ``` -------------------------------- ### Invalid Timezone Error Example Source: https://github.com/nestjs/schedule/blob/master/_autodocs/errors.md This example shows how providing an invalid timezone string to the @Cron decorator will throw an error. Always use valid timezone identifiers. ```typescript import { Injectable, } from '@nestjs/common'; import { Cron, CronExpression } from '@nestjs/schedule'; @Injectable() export class TasksService { @Cron(CronExpression.EVERY_HOUR, { timeZone: 'Invalid/Timezone', // Invalid timezone }) scheduleTask() {} } // Throws: Error: Timezone not found ``` -------------------------------- ### Get All Registered Interval Names Source: https://github.com/nestjs/schedule/blob/master/_autodocs/scheduler-registry.md Use `getIntervals` to get an array of strings, where each string is the name of a registered interval timer. This is useful for iterating through or logging all active intervals. ```typescript const intervals = this.schedulerRegistry.getIntervals(); console.log(intervals); // ['stats-sync', 'cache-refresh'] ``` -------------------------------- ### ScheduleModule Async Configuration with useExisting Source: https://github.com/nestjs/schedule/blob/master/_autodocs/configuration.md Illustrates configuring the ScheduleModule asynchronously by referencing an existing provider that implements ScheduleModuleOptionsFactory. This is useful for reusing an already configured service. ```typescript import { Module } from '@nestjs/common'; import { ScheduleModule } from '@nestjs/schedule'; @Module({ providers: [ScheduleConfigService], imports: [ ScheduleModule.forRootAsync({ useExisting: ScheduleConfigService, }), ], }) export class AppModule {} ``` -------------------------------- ### ScheduleModule Initialization - Async Configuration with useClass Source: https://github.com/nestjs/schedule/blob/master/_autodocs/schedule-module.md Configure ScheduleModule asynchronously using ScheduleModule.forRootAsync() with a useClass option. This involves creating a separate injectable class that implements ScheduleModuleOptionsFactory to provide configuration. ```typescript import { Injectable } from '@nestjs/common'; import { ScheduleModuleOptionsFactory, ScheduleModuleOptions } from '@nestjs/schedule'; @Injectable() export class ScheduleConfigService implements ScheduleModuleOptionsFactory { createScheduleOptions(): ScheduleModuleOptions { return { cronJobs: true, intervals: true, timeouts: false, }; } } @Module({ imports: [ ScheduleModule.forRootAsync({ useClass: ScheduleConfigService, }), ], }) export class AppModule {} ``` -------------------------------- ### Application Bootstrap - Mount Intervals Source: https://github.com/nestjs/schedule/blob/master/_autodocs/scheduler-orchestrator.md During application bootstrap, this step creates setInterval instances for all registered interval tasks. ```text mountIntervals() — Create setInterval instances ``` -------------------------------- ### ScheduleModule Async Configuration with Module Imports Source: https://github.com/nestjs/schedule/blob/master/_autodocs/configuration.md Demonstrates how to include additional modules when configuring the ScheduleModule asynchronously using `forRootAsync`. This is necessary if the factory or class depends on providers from other modules. ```typescript @Module({ imports: [ ScheduleModule.forRootAsync({ imports: [ConfigModule], useFactory: async (configService: ConfigService) => ({ cronJobs: configService.get('ENABLE_CRON'), intervals: configService.get('ENABLE_INTERVALS'), timeouts: configService.get('ENABLE_TIMEOUTS'), }), inject: [ConfigService], }), ], }) export class AppModule {} ``` -------------------------------- ### ScheduleModule Async Configuration with useFactory Source: https://github.com/nestjs/schedule/blob/master/_autodocs/configuration.md Demonstrates configuring the ScheduleModule asynchronously using a factory function. This pattern is useful when options depend on other services, like a ConfigService. ```typescript import { Module } from '@nestjs/common'; import { ScheduleModule } from '@nestjs/schedule'; import { ConfigService } from './config.service'; @Module({ imports: [ ScheduleModule.forRootAsync({ useFactory: async (configService: ConfigService) => ({ cronJobs: configService.get('ENABLE_CRON'), intervals: configService.get('ENABLE_INTERVALS'), timeouts: configService.get('ENABLE_TIMEOUTS'), }), inject: [ConfigService], }), ], }) export class AppModule {} ``` -------------------------------- ### getCronJob Source: https://github.com/nestjs/schedule/blob/master/_autodocs/scheduler-registry.md Retrieves a specific cron job by its registered name. This allows for direct manipulation of the job, such as stopping or starting it. ```APIDOC ## getCronJob ### Description Retrieves a cron job by name. ### Method N/A (Method of a service class) ### Parameters #### Path Parameters N/A #### Query Parameters N/A #### Request Body N/A #### Method Parameters - **name** (`string`) - Required - Name of the cron job ### Response #### Success Response - **CronJob** - The cron job instance (from the `cron` package) ### Throws - `Error` with message `No Cron Job was found with the given name (${name})` if not found ### Example ```typescript const job = this.schedulerRegistry.getCronJob('daily-report'); job.stop(); job.start(); ``` ``` -------------------------------- ### Using CronExpression with @Cron() Decorator Source: https://github.com/nestjs/schedule/blob/master/_autodocs/types.md Example of applying a predefined cron expression to a task using the @Cron() decorator. ```typescript import { Cron, CronExpression } from '@nestjs/schedule'; @Cron(CronExpression.EVERY_HOUR) scheduleTask() {} ``` -------------------------------- ### Application Bootstrap - Mount Timeouts Source: https://github.com/nestjs/schedule/blob/master/_autodocs/scheduler-orchestrator.md During application bootstrap, this step creates setTimeout instances for all registered timeout tasks. ```text mountTimeouts() — Create setTimeout instances ``` -------------------------------- ### Get Non-existent Interval Source: https://github.com/nestjs/schedule/blob/master/_autodocs/errors.md Illustrates trying to access an interval that doesn't exist in the registry, resulting in a NO_SCHEDULER_FOUND error. ```typescript const registry = app.get(SchedulerRegistry); const interval = registry.getInterval('missing-interval'); // Throws: Error: No Interval was found with the given name (missing-interval). // Check that you created one with a decorator or with the create API. ``` -------------------------------- ### Application Bootstrap - Mount Cron Jobs Source: https://github.com/nestjs/schedule/blob/master/_autodocs/scheduler-orchestrator.md During application bootstrap, this step creates CronJob instances for all registered cron tasks. ```text mountCron() — Create CronJob instances ``` -------------------------------- ### Get Non-existent Cron Job Source: https://github.com/nestjs/schedule/blob/master/_autodocs/errors.md Demonstrates attempting to retrieve a cron job that has not been registered. This will throw a NO_SCHEDULER_FOUND error. ```typescript const registry = app.get(SchedulerRegistry); const job = registry.getCronJob('non-existent-job'); // Throws: Error: No Cron Job was found with the given name (non-existent-job). // Check that you created one with a decorator or with the create API. ``` -------------------------------- ### NestJS Schedule Module Bootstrap Flow Source: https://github.com/nestjs/schedule/blob/master/_autodocs/overview.md Illustrates the sequence of events during application bootstrap when using the ScheduleModule, from module registration to task execution. ```text Application Bootstrap ↓ ScheduleModule.forRoot() / forRootAsync() ↓ DiscoveryModule finds all providers/controllers ↓ ScheduleExplorer discovers @Cron/@Interval/@Timeout decorators ↓ SchedulerMetadataAccessor reads decorator metadata ↓ SchedulerOrchestrator creates CronJob/setInterval/setTimeout instances ↓ Tasks registered in SchedulerRegistry ↓ Application initialization complete ↓ Scheduled tasks begin executing ``` -------------------------------- ### getIntervals Source: https://github.com/nestjs/schedule/blob/master/_autodocs/scheduler-registry.md Returns an array of names for all currently registered interval timers. This is useful for getting an overview of active intervals. ```APIDOC ## getIntervals ### Description Returns all registered interval names. ### Method N/A (Method of a service class) ### Parameters N/A ### Response #### Success Response - **string[]** - An array of interval names ### Example ```typescript const intervals = this.schedulerRegistry.getIntervals(); console.log(intervals); ``` ``` -------------------------------- ### Dynamic Task Registration Source: https://github.com/nestjs/schedule/blob/master/_autodocs/INDEX.md Shows how to dynamically register new cron jobs at runtime using the CronJob class and SchedulerRegistry. This allows for on-the-fly task creation. ```typescript addDynamicTask(name: string, cronTime: string) { const job = new CronJob(cronTime, () => { console.log(`Task ${name} executed`); }); this.registry.addCronJob(name, job); job.start(); } ``` -------------------------------- ### Common Interval Durations Source: https://github.com/nestjs/schedule/blob/master/_autodocs/decorators-interval.md Demonstrates setting up intervals for common time frequencies like every second, 5 seconds, minute, 5 minutes, and hour. Each interval is given a descriptive name. ```typescript @Injectable() export class TasksService { @Interval('every-second', 1000) everySecond() { console.log('1 second'); } @Interval('every-5-seconds', 5000) every5Seconds() { console.log('5 seconds'); } @Interval('every-minute', 60000) everyMinute() { console.log('1 minute'); } @Interval('every-5-minutes', 300000) every5Minutes() { console.log('5 minutes'); } @Interval('every-hour', 3600000) everyHour() { console.log('1 hour'); } } ``` -------------------------------- ### addCronJob Source: https://github.com/nestjs/schedule/blob/master/_autodocs/scheduler-registry.md Dynamically registers a new cron job with a given name. This allows for adding scheduled tasks at runtime after the application has started. ```APIDOC ## addCronJob ### Description Registers a new cron job dynamically. ### Method N/A (Method of a service class) ### Parameters #### Path Parameters N/A #### Query Parameters N/A #### Request Body N/A #### Method Parameters - **name** (`string`) - Required - Unique name for the cron job - **job** (`CronJob`) - Required - CronJob instance from the `cron` package ### Throws - `Error` with message `Cron Job with the given name (${name}) already exists. Ignored.` if a job with this name already exists ### Example ```typescript import { CronJob } from 'cron'; import { CronExpression } from '@nestjs/schedule'; const job = new CronJob(CronExpression.EVERY_HOUR, () => { console.log('Hourly task'); }); this.schedulerRegistry.addCronJob('hourly-task', job); job.start(); ``` ``` -------------------------------- ### Valid Timezone Usage Source: https://github.com/nestjs/schedule/blob/master/_autodocs/errors.md This example demonstrates the correct usage of the timeZone option in the @Cron decorator by providing a pre-validated timezone string. ```typescript import { Injectable, } from '@nestjs/common'; import { Cron, CronExpression } from '@nestjs/schedule'; const validTimezones = ['America/New_York', 'Europe/London', 'Asia/Tokyo']; @Injectable() export class TasksService { @Cron(CronExpression.EVERY_HOUR, { timeZone: validTimezones[0], // Use pre-validated timezone }) scheduleTask() {} } ``` -------------------------------- ### Using @Timeout Decorator Source: https://github.com/nestjs/schedule/blob/master/_autodocs/README.md Schedule a task to execute once after a specified delay using the @Timeout decorator. This example runs a task after 10 seconds. ```typescript import { Timeout } from '@nestjs/schedule'; @Injectable() export class MyTaskService { @Timeout(10000) // Runs once after 10 seconds handleTimeout() { console.log('Called once after 10 seconds'); } } ``` -------------------------------- ### ScheduleModule Initialization - Async Configuration with useFactory Source: https://github.com/nestjs/schedule/blob/master/_autodocs/schedule-module.md Utilize ScheduleModule.forRootAsync() with a useFactory function for asynchronous configuration. This approach allows injecting services like ConfigService to dynamically set scheduler options. ```typescript import { Module } from '@nestjs/common'; import { ScheduleModule } from '@nestjs/schedule'; @Module({ imports: [ ScheduleModule.forRootAsync({ useFactory: async (configService: ConfigService) => ({ cronJobs: configService.get('ENABLE_CRON'), intervals: true, timeouts: true, }), inject: [ConfigService], }), ], }) export class AppModule {} ``` -------------------------------- ### Feature Flag-Based Configuration for Schedule Module Source: https://github.com/nestjs/schedule/blob/master/_autodocs/configuration.md Configure schedule options asynchronously using feature flags. ```typescript @Injectable() export class ScheduleConfigService implements ScheduleModuleOptionsFactory { constructor(private featureFlagService: FeatureFlagService) {} async createScheduleOptions(): Promise { return { cronJobs: await this.featureFlagService.isEnabled('cron-jobs'), intervals: await this.featureFlagService.isEnabled('intervals'), timeouts: await this.featureFlagService.isEnabled('timeouts'), }; } } ``` -------------------------------- ### ScheduleModule Async Configuration with useClass Source: https://github.com/nestjs/schedule/blob/master/_autodocs/configuration.md Shows how to configure the ScheduleModule asynchronously by providing a class that implements ScheduleModuleOptionsFactory. The NestJS DI container will instantiate this class. ```typescript import { Injectable } from '@nestjs/common'; import { ScheduleModuleOptionsFactory, ScheduleModuleOptions } from '@nestjs/schedule'; @Injectable() export class ScheduleConfigService implements ScheduleModuleOptionsFactory { constructor(private configService: ConfigService) {} createScheduleOptions(): ScheduleModuleOptions { return { cronJobs: this.configService.get('ENABLE_CRON', true), intervals: this.configService.get('ENABLE_INTERVALS', true), timeouts: this.configService.get('ENABLE_TIMEOUTS', true), }; } } @Module({ imports: [ ScheduleModule.forRootAsync({ useClass: ScheduleConfigService, }), ], }) export class AppModule {} ``` -------------------------------- ### Health Check Initialization with @Timeout Source: https://github.com/nestjs/schedule/blob/master/_autodocs/decorators-timeout.md Perform an initial health check after a delay when the application starts using @Timeout. This is useful for verifying external dependencies. ```typescript import { Injectable } from '@nestjs/common'; import { Timeout } from '@nestjs/schedule'; // Assuming Database is a defined class or interface interface Database { ping(): Promise; } @Injectable() export class HealthService { constructor(private database: Database) {} @Timeout('initial-health-check', 10000) async performInitialHealthCheck() { try { const isHealthy = await this.database.ping(); console.log(`Initial health check: ${isHealthy ? 'PASS' : 'FAIL'}`); } catch (error) { console.error('Initial health check failed:', error); } } } ``` -------------------------------- ### Create a Service with Scheduled Tasks Source: https://github.com/nestjs/schedule/blob/master/_autodocs/quick-start.md Define a service (e.g., TasksService) and use decorators like @Cron, @Interval, and @Timeout to schedule methods. ```typescript import { Injectable } from '@nestjs/common'; import { Cron, Interval, Timeout, CronExpression } from '@nestjs/schedule'; @Injectable() export class TasksService { // Run every hour @Cron(CronExpression.EVERY_HOUR) handleCron() { console.log('Running cron job every hour'); } // Run every 10 seconds @Interval(10000) handleInterval() { console.log('Running every 10 seconds'); } // Run once after 5 seconds @Timeout(5000) handleTimeout() { console.log('Ran after 5 seconds'); } } ``` -------------------------------- ### ScheduleModuleAsyncOptions Source: https://github.com/nestjs/schedule/blob/master/_autodocs/types.md Options interface for `ScheduleModule.forRootAsync()`. It allows for asynchronous configuration of the Schedule Module by providing a factory function, a class, or an existing provider. ```APIDOC ## ScheduleModuleAsyncOptions Options interface for `ScheduleModule.forRootAsync()`. ### Fields - **useExisting** (`Type`) - Conditional - Existing provider to use for configuration - **useClass** (`Type`) - Conditional - Class to instantiate for configuration - **useFactory** (`(...args: any[]) => Promise | ScheduleModuleOptions`) - Conditional - Factory function to create configuration - **inject** (`any[]`) - No - Dependency tokens to inject into factory - **imports** (`ModuleMetadata['imports']`) - No - Modules to import for dependencies ### Example ```typescript const asyncOptions: ScheduleModuleAsyncOptions = { useFactory: (configService: ConfigService) => ({ cronJobs: configService.get('ENABLE_CRON'), intervals: true, timeouts: true, }), inject: [ConfigService], }; ``` ``` -------------------------------- ### Using @Cron Decorator Source: https://github.com/nestjs/schedule/blob/master/_autodocs/README.md Schedule tasks using calendar-based expressions with the @Cron decorator. This example demonstrates scheduling a task to run every minute. ```typescript import { Cron } from '@nestjs/schedule'; @Injectable() export class MyTaskService { @Cron('0 * * * * *') handleCron() { console.log('Called when the current second is 0'); } } ``` -------------------------------- ### Safely Get Cron Job Source: https://github.com/nestjs/schedule/blob/master/_autodocs/errors.md Provides a method to safely retrieve a cron job by using a try-catch block to handle potential NO_SCHEDULER_FOUND errors. ```typescript import { SchedulerRegistry, Injectable, } from '@nestjs/schedule'; @Injectable() export class TasksService { constructor(private registry: SchedulerRegistry) {} getCronJobSafely(name: string) { try { return this.registry.getCronJob(name); } catch (error) { console.error(`Cron job "${name}" not found`); return null; } } // Better: Check before accessing pauseJobIfExists(name: string) { if (this.registry.doesExist('cron', name)) { const job = this.registry.getCronJob(name); job.stop(); } } } ``` -------------------------------- ### ScheduleModule.forRoot() Source: https://github.com/nestjs/schedule/blob/master/_autodocs/schedule-module.md Registers the ScheduleModule with synchronous configuration options. This method enables all schedulers by default and can be configured to disable specific ones. ```APIDOC ## ScheduleModule.forRoot() ### Description Static method that registers the ScheduleModule with configuration options in synchronous mode. Creates a global module with all schedulers enabled by default. ### Method `static forRoot(options?: ScheduleModuleOptions): DynamicModule` ### Parameters #### Path Parameters None #### Query Parameters None #### Request Body None ### Parameters - **options** (`ScheduleModuleOptions`) - Optional - Module configuration options. - `cronJobs?: boolean` - Enable/disable cron job discovery (default: `true`) - `intervals?: boolean` - Enable/disable interval discovery (default: `true`) - `timeouts?: boolean` - Enable/disable timeout discovery (default: `true`) ### Request Example ```typescript // Enable all schedulers ScheduleModule.forRoot() // Disable specific schedulers ScheduleModule.forRoot({ cronJobs: true, intervals: false, timeouts: true, }) ``` ### Response #### Success Response (200) `DynamicModule` - A NestJS dynamic module marked as global, exporting `SchedulerRegistry`. #### Response Example None provided. ``` -------------------------------- ### Environment-Based Configuration for Schedule Module Source: https://github.com/nestjs/schedule/blob/master/_autodocs/configuration.md Implement ScheduleModuleOptionsFactory to provide configuration based on NODE_ENV. ```typescript @Injectable() export class ScheduleConfigService implements ScheduleModuleOptionsFactory { createScheduleOptions(): ScheduleModuleOptions { const isDevelopment = process.env.NODE_ENV === 'development'; const isProduction = process.env.NODE_ENV === 'production'; return { // Enable all in production, only cron jobs in development cronJobs: true, intervals: isProduction, timeouts: isProduction, }; } } ``` -------------------------------- ### Cron Job with SchedulerRegistry Access Source: https://github.com/nestjs/schedule/blob/master/_autodocs/decorators-cron.md Inject `SchedulerRegistry` to programmatically control cron jobs at runtime. You can retrieve jobs by their registered name to start, stop, or manage them. ```typescript import { Injectable } from '@nestjs/common'; import { Cron, CronExpression, SchedulerRegistry } from '@nestjs/schedule'; @Injectable() export class TasksService { constructor(private schedulerRegistry: SchedulerRegistry) {} @Cron(CronExpression.EVERY_HOUR, { name: 'pausable-job', }) executeJob() { console.log('Job executing'); } pauseJob() { const job = this.schedulerRegistry.getCronJob('pausable-job'); job.stop(); } resumeJob() { const job = this.schedulerRegistry.getCronJob('pausable-job'); job.start(); } } ``` -------------------------------- ### Cron Job with Initial Delay Source: https://github.com/nestjs/schedule/blob/master/_autodocs/decorators-cron.md Use `initialDelay` to postpone the first execution of a cron job. This is useful for allowing application resources to initialize before the job starts. ```typescript import { Injectable } from '@nestjs/common'; import { Cron, CronExpression } from '@nestjs/schedule'; @Injectable() export class TasksService { @Cron(CronExpression.EVERY_HOUR, { name: 'delayed-sync', initialDelay: 30000, // Wait 30 seconds after app starts }) syncWithExternalService() { console.log('Syncing with external service'); } } ```