You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

如何在NestJS中实现每日特定时间的Cron任务调度?

NestJS Cron任务调整为每日17点执行的方案

1. 修改Cron表达式

NestJS的@Cron()装饰器使用6位Cron表达式,格式为:秒 分 时 日 月 周。

你当前的表达式10 * * * * *表示「每分钟的第10秒执行一次」,要实现每日下午5点(17点)整执行,需将表达式改为:0 0 17 * * *,含义是:

  • 第0秒、第0分、17时,任意日期、任意月份、任意星期都执行。

修改后的代码如下:

@Cron('0 0 17 * * *')
async handleCron() {
  const country = await this.countryRepo.find();
  // 注意:原map的异步操作存在不等待的问题,建议调整为下面的写法
  await Promise.all(country.map(async (value) => {
      // ...执行你的业务逻辑
  }));
}

2. 修复异步遍历的潜在问题

原代码中country.map(async (value) => { ... })的写法不会等待所有异步操作完成,任务会提前结束。如果需要确保所有国家的业务逻辑都执行完毕后再结束Cron任务,推荐使用Promise.all()包裹map结果,或者改用for...of循环:

// 用for...of的写法(更直观)
@Cron('0 0 17 * * *')
async handleCron() {
  const country = await this.countryRepo.find();
  for (const value of country) {
      // ...执行你的业务逻辑
      await this.someAsyncOperation(value);
  }
}

内容的提问来源于stack exchange,提问作者Md. Golam Rabbani

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.08.19 15:05:19