繁体   English   中英

NestJs 在 @Cron 装饰器上使用环境配置

[英]NestJs Using Environment Configuration on @Cron decorator

我正在构建一个带有调度和配置的 nestJs 应用程序。 我希望能够使用我的环境变量配置我的 Cron,但它似乎不起作用。

app.module.ts :

@Module({
  imports: [
    ConfigModule.forRoot(),
    ScheduleModule.forRoot(),
    SchedulingModule,
    ...
  ],
})
export class AppModule {}

schedule.service.ts(来自我的 SchedulingModule):

@Cron(process.env.CRON_VALUE)
scheduledJob() {
  this.logger.log('Scheduled : Job');
  ...
}

.env :

...
CRON_VALUE=0 4 * * *
...

显然,目前检查该值是空的。 我收到以下错误:

(node:55016) UnhandledPromiseRejectionWarning: TypeError: Cannot read property '_isAMomentObject' of undefined
    at new CronTime (/Users/antoinegrenard/Documents/Projet/b4finance/service-scheduling/node_modules/cron/lib/cron.js:42:50)
    at new CronJob (/Users/antoinegrenard/Documents/Projet/b4finance/service-scheduling/node_modules/cron/lib/cron.js:527:19)
    at /Users/antoinegrenard/Documents/Projet/b4finance/service-scheduling/node_modules/@nestjs/schedule/dist/scheduler.orchestrator.js:56:29 
    ...

要解决此问题,您应该再次在您的服务上加载配置:

require('dotenv').config();

显然,不可能在装饰器中获得 env 值。

我不得不这样做:

constructor(private schedulerRegistry: SchedulerRegistry) {}

onModuleInit() {
  const job = new CronJob(process.env. CRON_VALUE, () => {
    // What you want to do here
  });

  this.schedulerRegistry.addCronJob(name, job);
  job.start();
}

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM