training_data/apps/server/src/tasks/tasks.service.ts

47 lines
1.8 KiB
TypeScript
Raw Normal View History

2024-09-03 20:19:33 +08:00
import { Injectable, Logger, OnModuleInit } from '@nestjs/common';
import { SchedulerRegistry } from '@nestjs/schedule';
2024-12-30 08:26:40 +08:00
import { InitService } from '@server/tasks/init/init.service';
import { ReminderService } from '@server/tasks/reminder/reminder.service';
2024-09-03 20:19:33 +08:00
import { CronJob } from 'cron';
@Injectable()
export class TasksService implements OnModuleInit {
private readonly logger = new Logger(TasksService.name);
constructor(
private readonly schedulerRegistry: SchedulerRegistry,
private readonly initService: InitService,
2024-12-30 08:26:40 +08:00
private readonly reminderService: ReminderService
2024-09-03 20:19:33 +08:00
) { }
async onModuleInit() {
this.logger.log('Main node launch');
2025-01-10 21:36:17 +08:00
await this.initService.init();
this.logger.log('Initialization successful');
2024-09-03 20:19:33 +08:00
2024-12-30 08:26:40 +08:00
try {
const cronExpression = process.env.DEADLINE_CRON;
if (!cronExpression) {
throw new Error('DEADLINE_CRON environment variable is not set');
}
2024-09-03 20:19:33 +08:00
2024-12-30 08:26:40 +08:00
const handleRemindJob = new CronJob(cronExpression, async () => {
try {
await this.reminderService.remindDeadline();
this.logger.log('Reminder successfully processed');
} catch (reminderErr) {
this.logger.error('Error occurred while processing reminder', reminderErr);
}
});
this.schedulerRegistry.addCronJob('remindDeadline', handleRemindJob as any);
this.logger.log('Start remind cron job');
handleRemindJob.start();
} catch (cronJobErr) {
this.logger.error('Failed to initialize cron job', cronJobErr);
// Optionally rethrow the error if you want to halt further execution
// throw cronJobErr;
}
2024-09-03 20:19:33 +08:00
}
}