实现定时任务调度服务
- 创建 SchedulerService 调度服务 - 支持采集任务定时调度 - 支持报告生成任务定时调度 - 支持手动触发任务 - 支持动态加载和重载任务 Co-Authored-By: Claude Opus 4.5 <noreply@anthropic.com>
This commit is contained in:
1 parent
5746676819
commit
881bbb64a3
1 file changed
+168
@@ -0,0 +1,168 @@
|
|||||||
|
import cron, { ScheduledTask } from 'node-cron';
|
||||||
|
import { CollectorService } from './collector.service';
|
||||||
|
import { ReportService } from './report.service';
|
||||||
|
import { DistributorService } from './distributor.service';
|
||||||
|
import prisma from '../config/database';
|
||||||
|
import logger from '../utils/logger';
|
||||||
|
|
||||||
|
interface ScheduledTaskInfo {
|
||||||
|
id: string;
|
||||||
|
type: 'collection' | 'report';
|
||||||
|
cronExpression: string;
|
||||||
|
task: ScheduledTask;
|
||||||
|
resourceId: number;
|
||||||
|
}
|
||||||
|
|
||||||
|
export class SchedulerService {
|
||||||
|
private tasks: Map<string, ScheduledTaskInfo> = new Map();
|
||||||
|
private collectorService: CollectorService;
|
||||||
|
private reportService: ReportService;
|
||||||
|
private distributorService: DistributorService;
|
||||||
|
|
||||||
|
constructor() {
|
||||||
|
this.collectorService = new CollectorService();
|
||||||
|
this.reportService = new ReportService();
|
||||||
|
this.distributorService = new DistributorService();
|
||||||
|
}
|
||||||
|
|
||||||
|
async start(): Promise<void> {
|
||||||
|
logger.info('启动调度器...');
|
||||||
|
await this.loadCollectionTasks();
|
||||||
|
await this.loadReportTasks();
|
||||||
|
logger.info(`调度器启动完成,共 ${this.tasks.size} 个任务`);
|
||||||
|
}
|
||||||
|
|
||||||
|
stop(): void {
|
||||||
|
logger.info('停止调度器...');
|
||||||
|
this.tasks.forEach((task) => task.task.stop());
|
||||||
|
this.tasks.clear();
|
||||||
|
logger.info('调度器已停止');
|
||||||
|
}
|
||||||
|
|
||||||
|
private async loadCollectionTasks(): Promise<void> {
|
||||||
|
const sources = await prisma.source.findMany({ where: { enabled: true } });
|
||||||
|
logger.info(`加载 ${sources.length} 个采集任务`);
|
||||||
|
|
||||||
|
for (const source of sources) {
|
||||||
|
this.scheduleCollectionTask(source.id, source.cronExpression);
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
private async loadReportTasks(): Promise<void> {
|
||||||
|
const topics = await prisma.topic.findMany({ where: { enabled: true } });
|
||||||
|
logger.info(`加载 ${topics.length} 个报告生成任务`);
|
||||||
|
|
||||||
|
for (const topic of topics) {
|
||||||
|
const scheduleConfig = topic.scheduleConfig as any;
|
||||||
|
if (scheduleConfig?.cron) {
|
||||||
|
this.scheduleReportTask(topic.id, scheduleConfig.cron);
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
scheduleCollectionTask(sourceId: number, cronExpression: string): void {
|
||||||
|
const taskId = `collection-${sourceId}`;
|
||||||
|
|
||||||
|
if (this.tasks.has(taskId)) {
|
||||||
|
this.unscheduleTask(taskId);
|
||||||
|
}
|
||||||
|
|
||||||
|
if (!cron.validate(cronExpression)) {
|
||||||
|
logger.error(`无效的 cron 表达式: ${cronExpression}`, { sourceId });
|
||||||
|
return;
|
||||||
|
}
|
||||||
|
|
||||||
|
const task = cron.schedule(cronExpression, async () => {
|
||||||
|
logger.info(`执行采集任务: sourceId=${sourceId}`);
|
||||||
|
try {
|
||||||
|
await this.collectorService.collectSource(sourceId);
|
||||||
|
} catch (error) {
|
||||||
|
logger.error('采集任务执行失败', { sourceId, error });
|
||||||
|
}
|
||||||
|
});
|
||||||
|
|
||||||
|
this.tasks.set(taskId, {
|
||||||
|
id: taskId,
|
||||||
|
type: 'collection',
|
||||||
|
cronExpression,
|
||||||
|
task,
|
||||||
|
resourceId: sourceId,
|
||||||
|
});
|
||||||
|
|
||||||
|
logger.info(`采集任务已调度: sourceId=${sourceId}, cron=${cronExpression}`);
|
||||||
|
}
|
||||||
|
|
||||||
|
scheduleReportTask(topicId: number, cronExpression: string): void {
|
||||||
|
const taskId = `report-${topicId}`;
|
||||||
|
|
||||||
|
if (this.tasks.has(taskId)) {
|
||||||
|
this.unscheduleTask(taskId);
|
||||||
|
}
|
||||||
|
|
||||||
|
if (!cron.validate(cronExpression)) {
|
||||||
|
logger.error(`无效的 cron 表达式: ${cronExpression}`, { topicId });
|
||||||
|
return;
|
||||||
|
}
|
||||||
|
|
||||||
|
const task = cron.schedule(cronExpression, async () => {
|
||||||
|
logger.info(`执行报告生成任务: topicId=${topicId}`);
|
||||||
|
try {
|
||||||
|
const reportId = await this.reportService.generateReportForTopic(topicId);
|
||||||
|
await this.distributorService.distributeReportToAllChannels(reportId);
|
||||||
|
} catch (error) {
|
||||||
|
logger.error('报告生成任务执行失败', { topicId, error });
|
||||||
|
}
|
||||||
|
});
|
||||||
|
|
||||||
|
this.tasks.set(taskId, {
|
||||||
|
id: taskId,
|
||||||
|
type: 'report',
|
||||||
|
cronExpression,
|
||||||
|
task,
|
||||||
|
resourceId: topicId,
|
||||||
|
});
|
||||||
|
|
||||||
|
logger.info(`报告生成任务已调度: topicId=${topicId}, cron=${cronExpression}`);
|
||||||
|
}
|
||||||
|
|
||||||
|
unscheduleTask(taskId: string): void {
|
||||||
|
const scheduledTask = this.tasks.get(taskId);
|
||||||
|
if (scheduledTask) {
|
||||||
|
scheduledTask.task.stop();
|
||||||
|
this.tasks.delete(taskId);
|
||||||
|
logger.info(`任务已取消: ${taskId}`);
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
async reload(): Promise<void> {
|
||||||
|
logger.info('重新加载调度任务...');
|
||||||
|
this.stop();
|
||||||
|
await this.start();
|
||||||
|
}
|
||||||
|
|
||||||
|
getTasksStatus(): Array<{
|
||||||
|
id: string;
|
||||||
|
type: string;
|
||||||
|
cronExpression: string;
|
||||||
|
resourceId: number;
|
||||||
|
}> {
|
||||||
|
return Array.from(this.tasks.values()).map((task) => ({
|
||||||
|
id: task.id,
|
||||||
|
type: task.type,
|
||||||
|
cronExpression: task.cronExpression,
|
||||||
|
resourceId: task.resourceId,
|
||||||
|
}));
|
||||||
|
}
|
||||||
|
|
||||||
|
async triggerCollection(sourceId: number): Promise<void> {
|
||||||
|
logger.info(`手动触发采集任务: sourceId=${sourceId}`);
|
||||||
|
await this.collectorService.collectSource(sourceId);
|
||||||
|
}
|
||||||
|
|
||||||
|
async triggerReport(topicId: number): Promise<number> {
|
||||||
|
logger.info(`手动触发报告生成任务: topicId=${topicId}`);
|
||||||
|
const reportId = await this.reportService.generateReportForTopic(topicId);
|
||||||
|
await this.distributorService.distributeReportToAllChannels(reportId);
|
||||||
|
return reportId;
|
||||||
|
}
|
||||||
|
}
|
||||||
Reference in new issue
Block a user