import { Inject, Injectable, Logger, type OnModuleInit, type OnModuleDestroy, } from '@nestjs/common'; import cron from 'node-cron'; import { SummarizationService } from './summarization.service.js'; @Injectable() export class CronService implements OnModuleInit, OnModuleDestroy { private readonly logger = new Logger(CronService.name); private readonly tasks: cron.ScheduledTask[] = []; constructor(@Inject(SummarizationService) private readonly summarization: SummarizationService) {} onModuleInit(): void { const summarizationSchedule = process.env['SUMMARIZATION_CRON'] ?? '0 */6 * * *'; // every 6 hours const tierManagementSchedule = process.env['TIER_MANAGEMENT_CRON'] ?? '0 3 * * *'; // daily at 3am this.tasks.push( cron.schedule(summarizationSchedule, () => { this.summarization.runSummarization().catch((err) => { this.logger.error(`Scheduled summarization failed: ${err}`); }); }), ); this.tasks.push( cron.schedule(tierManagementSchedule, () => { this.summarization.runTierManagement().catch((err) => { this.logger.error(`Scheduled tier management failed: ${err}`); }); }), ); this.logger.log( `Cron scheduled: summarization="${summarizationSchedule}", tier="${tierManagementSchedule}"`, ); } onModuleDestroy(): void { for (const task of this.tasks) { task.stop(); } this.tasks.length = 0; this.logger.log('Cron tasks stopped'); } }