原帖
启动
npm install --save @nestjs/schedule
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18
| import { ScheduleModule } from "@nestjs/schedule"; @Module({ imports: [ScheduleModule.forRoot()], controllers: [AppController], providers: [AppService, TaskService], }) export class AppModule {}
import { Cron, CronExpression } from "@nestjs/schedule"; @Injectable() export class TaskService { @Cron(CronExpression.EVERY_5_SECONDS) handleCron() { console.log("[task execute]"); } }
|
还有 <font style="color:rgb(37, 41, 51);">@Interval</font>
指定任务的执行间隔;<font style="color:rgb(37, 41, 51);">@Timeout</font>
指定多长时间后执行一次
| @Interval(3000) handleCron() { console.log('[task execute]', this.aaaService.findAll()); }
@Timeout('task3', 3000) task3() { console.log('task3'); }
|
使用 <font style="color:rgb(37, 41, 51);">SchedulerRegistery</font>
来对定时任务做增删改查。
新增 cron 任务得先安装 <font style="color:rgb(37, 41, 51);">npm install --save cron</font>
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49
| export class AppModule implements OnApplicationBootstrap { @Inject(SchedulerRegistry) private schedulerRegistry: SchedulerRegistry;
onApplicationBootstrap() { const crons = this.schedulerRegistry.getCronJobs(); crons.forEach((item, key) => { item.stop(); this.schedulerRegistry.deleteCronJob(key); });
const intervals = this.schedulerRegistry.getIntervals(); intervals.forEach((item) => { const interval = this.schedulerRegistry.getInterval(item); clearInterval(interval);
this.schedulerRegistry.deleteInterval(item); });
const timeouts = this.schedulerRegistry.getTimeouts(); timeouts.forEach((item) => { const timeout = this.schedulerRegistry.getTimeout(item); clearTimeout(timeout);
this.schedulerRegistry.deleteTimeout(item); });
console.log(this.schedulerRegistry.getCronJobs()); console.log(this.schedulerRegistry.getIntervals()); console.log(this.schedulerRegistry.getTimeouts());
const job = new CronJob(`0/5 * * * * *`, () => { console.log("cron job"); });
this.schedulerRegistry.addCronJob("job1", job); job.start();
const interval = setInterval(() => { console.log("interval job"); }, 3000); this.schedulerRegistry.addInterval("job2", interval);
const timeout = setTimeout(() => { console.log("timeout job"); }, 5000); this.schedulerRegistry.addTimeout("job3", timeout); } }
|
cron 定义
nest 使用得定时系统是基于 Unix-like 操作系统中用于定时执行任务的工具 **cron**
, 完全可以叫 chatgpt 帮助你来定义, (跟 jenkins 的还是有区别的,jenkins 还支持 H 符号来分散负载)

其中年是可选的,所以一般都是 6 个。格式:秒 分 小时 日期 月份 星期 <年>
,每个字段都可以写* ,比如秒写 *就代表每秒都会触发,日期写 * 就代表每天都会触发。
但当你指定了<font style="color:rgb(37, 41, 51);">具体的日期</font>
的时候,由于不知道是星期几,如果写*表示那天都会执行,自然会冲突,所以当指定了具体的日期的时候,<font style="color:rgb(37, 41, 51);">星期得写?</font>
,相反星期确定时,日期就应该写 ? 啦
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23
| 7 12 13 10 * ?
0 20-30 * * * *
0 5,10 * * * *
0 5/10 * * * *
* * * ? * L
* * * L * ?
* * * W * ?
* * * 2W * ?
* * * LW * ?
* * * ? * 4
* * * ? * 1
|
更多