node.js - 未为 cron 作业定义注入(inject)服务

标签 node.js cron nestjs

尝试每天中午 12 点运行 cron 作业,但是,作业期间调用的服务未定义。

当调用端点时,逻辑工作得很好,但当 cron 任务运行代码时,逻辑就会失败。我注入(inject)的所有服务均未定义。

类型错误:无法读取未定义的属性“deleteAllDailyReviews”

类型错误:无法读取未定义的属性“getAllUsers”

我尝试将 this 绑定(bind)到任务,但是问题仍然存在。

  • Nest版本:6.5.3
  • Node 版本:10.16.0
  • 平台:Windows

计划任务:

import { UserService } from '../user/services/user.service';
import { UserWordService } from '../user/services/user-word.service';
import { schedule, ScheduleOptions, ScheduledTask } from 'node-cron';
import moment from 'moment';
import { parseExpression } from 'cron-parser';
import { ReviewService } from '../review/review.service';

@Injectable()
export class UtilitiesService {


    private options: ScheduleOptions = {
        scheduled: false
    };
    private task: ScheduledTask;

    constructor (
        private readonly userService: UserService,
        private readonly userWordService: UserWordService,
        private readonly reviewService: ReviewService,
    ) {
        this.task = schedule(environment.cronnJobExpression
            , this.executeCronJob.bind(this)
            , this.options);

    }

    public startJob() {
        this.task.start();
    }

    public async executeCronJob () {
        const format = 'YYYY-MM-DD hh:mm:ss';
        console.info(`Starting cron job at: ${moment().format(format)}`);

        try {
            await this.reviewService.deleteAllDailyReviews();
        } catch (e) {
            console.info(`updateAllWords failed \n`, e);
        }
        let users: any;
        try {
            users = await this.userService.getAllUsers();
        } catch (e) {
            console.info(`getAllUsers failed \n`, e);
        }

        if (users) {
            //
        }

        return;
    }
}

模块声明:

@Module({
  imports: [
    //
    UtilitiesModule,
   //
  ],
  controllers: [AppController],
})
export class AppModule {
  constructor(
    private readonly utilitiesService: UtilitiesService
  ) {
    this.utilitiesService.startJob();
  }
}

应该定义并运行注入(inject)服务中的所有方法。从 Controller 调用executeCronJob 方法时逻辑是合理的,但在cron 作业期间则不然。

最佳答案

将任务定义移动到 startJob 方法对我来说是这样。感谢 Kim Kern 的帮助。

public startJob() {
   this.task = schedule(
       environment.cronnJobExpression,
       this.executeCronJob.bind(this),
       this.options);

   this.task.start();
}

关于node.js - 未为 cron 作业定义注入(inject)服务,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/57553369/

相关文章:

cookies - 如何为 graphql 订阅实现身份验证防护(passportjs + cookies)

node.js - nodejs ejs 包含意外的标识符

node.js - AWS Lambda 异步并发限制

ruby-on-rails - 在 sidekiq-cron 中比较日期时出错

bash - cron 脚本不会像它应该的那样重新启动

redis - 我如何知道nestjs/bull确实连接到了redis?

Node.js fs.readdir 递归目录搜索

Node.js项目无网部署

python - Python matplotlib 作为 cron 作业运行时出现 QxcbConnection 错误

typescript - 如何用Jest单元测试覆盖TypeORM @Column装饰器?