node.js - 为 cron 作业注入的服务未定义
问题描述
尝试在每天上午 12 点运行 cron 作业,但是,在作业期间调用的服务是未定义的。
当调用端点时,逻辑工作得很好,当 cron 任务运行代码时它就会失败。我所有注入的服务都是未定义的。
TypeError: Cannot read property 'deleteAllDailyReviews' of undefined
TypeError: Cannot read property 'getAllUsers' of undefined
我尝试绑定this
到任务,但是问题仍然存在。
- 嵌套版本:6.5.3
- 节点版本:10.16.0
- 平台:视窗
定时任务:
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 作业期间不是。
解决方案
将任务定义移动到startJob
方法中为我做到了。感谢金克恩的帮助。
public startJob() {
this.task = schedule(
environment.cronnJobExpression,
this.executeCronJob.bind(this),
this.options);
this.task.start();
}
推荐阅读
- excel - 如何将文件保存到当年的文件夹?
- ios - App Store Connect 拒绝发布“Info.plist 中缺少目的字符串”的应用程序发布,但该应用程序不需要这些权限
- xaml - 无法将图像绑定到 Xamarin 表单中的 ListView
- javascript - 如何处理缓慢的 jQuery addClass 效果?
- node.js - 写入密码时出现 authTagLength 错误
- reactjs - 如何使用我的输入值更新 api 结果?
- amazon-web-services - 如何将调用方 IAM 策略应用于 lambda 函数执行?
- node.js - socket.io - 引擎错误握手以传输 websocket
- c++ - 将结构化绑定与“类元组”绑定协议一起使用时的标识符类型
- node.js - 写入磁盘的 NodeJS 不需要的字符