【问题标题】:NestJs Cron ServiceNestJs Cron 服务
【发布时间】:2021-12-17 00:59:37
【问题描述】:

我正在尝试使用 nestJs 的 Cron 装饰器创建计划服务

我在下面有一个 Cron 装饰的方法:

@Cron(CronExpression.EVERY_5_SECONDS)
  triggerDataloaderCron() {
    this.logger.debug('called every 10 seconds');
    return this.healthService.getPCFHealth();
  }

而这个 cron 作业调用另一个服务中的方法,如下图所示

getHealth() {
    //code to form up an endpoint, saved as the variable fullUrl

//Does not come into this block
    return this.httpService.get(fullUrl).pipe(
      map((axiosResponse: AxiosResponse) => {
        return axiosResponse.data;
      }),
      catchError((err) => {
        console.log("in error", err);
        throw new CustomException(ExceptionConstants.EurekaConnectionException);
      })
    );
  }

当 cron 作业运行时,我可以进入 getHealth() 方法,但是 this.httpService 等代码块没有运行。

关于如何实现这一点有什么建议吗?或者如果我以错误的方式处理这个问题?

谢谢!

【问题讨论】:

    标签: cron scheduled-tasks nestjs httpservice


    【解决方案1】:

    getHealth 方法返回一个 Observable。除非至少有一个订阅者,否则 observable 不会执行。

    在您的 cron 方法中,按如下方式添加订阅:

    this.healthService.getPCFHealth()
     .subscribe(response => console.log(response))
    

    由于 cron 方法定期执行,我认为您不需要从中返回值。

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2021-01-12
      • 1970-01-01
      • 2020-05-29
      • 2019-08-29
      • 2020-06-09
      • 2020-02-04
      • 1970-01-01
      • 2020-09-09
      相关资源
      最近更新 更多