首页 > 解决方案 > 为 cron 作业注入的服务未定义

问题描述

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

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

TypeError: Cannot read property 'deleteAllDailyReviews' of undefined

TypeError: Cannot read property 'getAllUsers' of undefined

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

定时任务:

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();
  }
}

应定义并运行来自注入服务的所有方法。当从控制器调用 executeCronJob 方法时,逻辑是合理的,只是在 cron 作业期间不是。

标签: node.jscronnestjs

解决方案


将任务定义移动到startJob方法中为我做到了。感谢金克恩的帮助。

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

   this.task.start();
}

推荐阅读