Create Task Scheduler
- Task scheduling allows you to schedule arbitrary code (methods/functions) to execute at a fixed date/time, at recurring intervals, or once after a specified interval.
- In the Linux world, this is often handled by packages like cron at the OS level.
npm install --save @nestjs/schedule
export interface Cat {
name: string;
age: number;
}
Add module in app
import { Module } from '@nestjs/common';
import { ScheduleModule } from '@nestjs/schedule';
@Module({
imports: [
ScheduleModule.forRoot()
],
})
export class AppModule {}
Create Scheduler class
import { Injectable, Logger } from '@nestjs/common';
import { Cron } from '@nestjs/schedule';
@Injectable()
export class TasksService {
private readonly logger = new Logger(TasksService.name);
@Cron('45 * * * * *')
handleCron() {
this.logger.debug('Called when the current second is 45');
}
}
Cron Expression
| Cron Expression | Description |
|---|---|
| * * * * * * | every second |
| 45 * * * * * | every minute, on the 45th second |
| 0 10 * * * * | every hour, at the start of the 10th minute |
| 0 */30 9-17 * * * | every 30 minutes between 9am and 5pm |
| 0 30 11 * * 1-5 | Monday to Friday at 11:30am |
* * * * * * *
| | | | | |
| | | | | day of week
| | | | months
| | | day of month
| | hours
| minutes
seconds (optional)