NestJs Cron 服务
Posted
技术标签:
【中文标题】NestJs Cron 服务【英文标题】:NestJs Cron Service 【发布时间】: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 等代码块没有运行。
关于如何实现这一点有什么建议吗?或者如果我以错误的方式处理这个问题?
谢谢!
【问题讨论】:
【参考方案1】:getHealth 方法返回一个 Observable。除非至少有一个订阅者,否则 observable 不会执行。
在您的 cron 方法中,按如下方式添加订阅:
this.healthService.getPCFHealth()
.subscribe(response => console.log(response))
由于 cron 方法定期执行,我认为您不需要从中返回值。
【讨论】:
以上是关于NestJs Cron 服务的主要内容,如果未能解决你的问题,请参考以下文章