Nest.JS Scheduler is a easy scheduler manager (Cron, Interval, Delay) for Nest.JS framework. Enables you to schedule tasks and manage their execution, from decorator or programmatically.
- Install dependency
npm i @sco-techlab/nestjs-scheduler
- Import SchedulerModule module in your 'app.module.ts' file with register method
import { Module } from '@nestjs/common'; import { SchedulerModule } from '@app/nestjs-scheduler'; @Module({ imports: [ SchedulerModule.register(), ], }) export class AppModule {}
- Module import is global mode, to use gridfs service only need to provide constructor dependency inyection
export type ExecutionType = 'Cron' | 'Interval' | 'Delay' | 'RunAt'; export class ScheduleTask { type: ExecutionType; // Type of execution name: string; // Name of the task, must be unique options: ScheduleOptions; // Options / parameters of the task context: any; // Context to execute fn?: any; // Function to execute object?: any; // Object to save the execution response?: any; // Response of the execution } export interface ScheduleOptions { priority?: number; // Priority of execution of initial decorator tasks cronTime?: string; // Cron time value for cron tasks ms?: number; // Milliseconds value for interval tasks runAt?: Date; // Date value for runAt tasks timeZone?: string; // Timezone value for cron and runAt tasks, on runAt }
import { Injectable } from "@nestjs/common"; import { of } from "rxjs"; import { Schedule, SchedulerContext, SchedulerService, ScheduleTask } from "@app/nestjs-scheduler"; @Injectable() export class CronesService extends SchedulerContext { private cronesServiceExecutionCounter: number = 0; constructor(private readonly schedulerService: SchedulerService) { super(schedulerService); // Add Programatically Cron Task this.schedulerService.addTasks( { type: 'Cron', name: 'crones_cron_1_service', options: { cronTime: '*/5 * * * * *', }, context: this, fn: async () => { this.cronesServiceExecutionCounter++; return of(this.cronesServiceExecutionCounter); } }, ); // Subscribe to Programatically task this.schedulerService.subscribeToTask('crones_cron_1_service').subscribe((data: ScheduleTask) => { console.log("Sub crones_cron_1_service: " + data?.response) }); // Subscribe to Decorator task this.schedulerService.subscribeToTask('crones_cron_1_decorator').subscribe((data: ScheduleTask) => { console.log("Sub crones_cron_1_decorator: " + data?.response) }); } @Schedule('Cron', 'crones_cron_1_decorator', { cronTime: '*/5 * * * * *', }) async handleTask() { return of(this.cronesServiceExecutionCounter); } }
- Live coding: Stackblitz example
Santiago Comeras Oteo