尝试每天凌晨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作业期间。
答案 0 :(得分:0)
将任务定义移动到startJob
方法对我来说是成功的。感谢Kim Kern的帮助。
public startJob() {
this.task = schedule(
environment.cronnJobExpression,
this.executeCronJob.bind(this),
this.options);
this.task.start();
}