安装插件
pnpm add cron
pnpm add @nestjs/schedule -D
自定义定时任务服务
@@filename(task.service.ts)
import { HttpException, HttpStatus, Injectable } from '@nestjs/common'
import { SchedulerRegistry } from '@nestjs/schedule'
import { CronJob } from 'cron'
// 自定义定时任务服务
@Injectable()
export class TaskService {
constructor(
// 定时任务注册器
private readonly schedulerRegistry: SchedulerRegistry,
) {}
// 执行任务
public async executeTask(
// 任务名称
name: string,
// cron表达式
cronExpression: Date | string,
// 回调函数
callback: () => void,
// 执行完后是否需要删除
needDel?: boolean
) {
try {
// 创建定时任务
const job: CronJob = new CronJob(cronExpression, () => {
if (callback) {
callback()
// 删除定时任务
needDel && this.deleteCron(name)
}
})
// 添加定时任务
this.schedulerRegistry.addCronJob(name, job)
// 启动定时任务
job.start()
} catch (e) {
throw new HttpException(e, HttpStatus.BAD_REQUEST)
}
}
// 删除任务
private deleteCron(name: string) {
this.schedulerRegistry.deleteCronJob(name)
}
}
定时任务模块
import { Module } from '@nestjs/common'
import { ScheduleModule } from '@nestjs/schedule'
import { TaskService } from './task.service'
// 定时任务模块
@Module({
imports: [
ScheduleModule.forRoot()
],
providers: [ TaskService ],
exports: [ TaskService ]
})
export class TaskModule {}
使用定时任务服务(以UserModule为例)
user.module.ts
@@filename(user.module.ts)
import { Module } from '@nestjs/common'
import { UserService } from './user.service'
import { UserController } from './user.controller'
import { TaskModule } from 'src/common/task/task.module'
@Module({
imports: [
TaskModule
],
controllers: [ UserController ],
providers: [ UserService ],
})
export class UserModule {}
user.service.ts
@@filename(user.service.ts)
import { HttpException, HttpStatus, Injectable } from '@nestjs/common'
import { TaskService } from 'src/common/task/task.service'
@Injectable()
export class UserService {
constructor(
private readonly taskService: TaskService,
) {}
async create(id: number, date: Date) {
try {
return await this.taskService.executeTask(
`user-${id}`,
new Date(date),
() => {
console.log('执行任务')
},
true
)
} catch (e) {
throw new HttpException(e, HttpStatus.BAD_REQUEST)
}
}
}
个人博客:https://www.linmeimei.top/ 欢迎访问