Que*_*n3r 2 javascript node.js typescript nestjs
我想为我的 NestJs 应用程序创建一个计划任务。它应该每 X 秒执行一次,因此我使用此处描述的间隔。
该应用程序使用配置文件,因此我可以使用保持间隔可配置。但是我如何将变量传递给 Typescript 装饰器呢?
NestJs为计划任务提供示例存储库
所以根据样本我想要类似的东西
@Injectable()
export class TasksService {
constructor(
private readonly myConfigService: MyConfigService,
) {}
@Interval(this.myConfigService.intervalInMilliseconds)
handleInterval() {
// ...
}
}
Run Code Online (Sandbox Code Playgroud)
我必须按照SchedulerRegistry文档中的描述使用吗?看来这对于标准 Typescript 来说是不可能的,请参阅此线程。
使用声明式 API(注释)这是不可能的,您必须动态注册 cron 作业(请参阅文档):
@Injectable()
export class TasksService implements OnModuleInit {
constructor(
private readonly myConfigService: MyConfigService,
private readonly schedulerRegistry: SchedulerRegistry,
) {}
onModuleInit() {
const interval = setInterval(() => this.handleInterval, this.myConfigService.intervalInMs);
this.schedulerRegistry.addInterval('my-dynamic-interval', interval);
}
handleInterval() {
// ...
}
}
Run Code Online (Sandbox Code Playgroud)
| 归档时间: |
|
| 查看次数: |
2877 次 |
| 最近记录: |