定时任务支持多个定时规则

This commit is contained in:
whyour
2023-09-16 00:15:50 +08:00
parent 042d7d3b8e
commit acc7443004
17 changed files with 305 additions and 274 deletions
+23 -8
View File
@@ -5,16 +5,15 @@ import { scheduleStacks } from './data';
import { runCron } from '../shared/runCron';
import { QL_PREFIX, TASK_PREFIX } from '../config/const';
import Logger from '../loaders/logger';
import dayjs from 'dayjs';
const addCron = (
call: ServerUnaryCall<AddCronRequest, AddCronResponse>,
callback: sendUnaryData<AddCronResponse>,
) => {
for (const item of call.request.crons) {
const { id, schedule, command } = item;
const { id, schedule, command, extraSchedules } = item;
if (scheduleStacks.has(id)) {
scheduleStacks.get(id)?.cancel();
scheduleStacks.get(id)?.forEach((x) => x.cancel());
}
let cmdStr = command.trim();
@@ -29,15 +28,31 @@ const addCron = (
command,
);
scheduleStacks.set(
id,
nodeSchedule.scheduleJob(id, schedule, async () => {
if (extraSchedules?.length) {
extraSchedules.forEach(x => {
Logger.info(
`[schedule][准备运行任务] 命令: ${cmdStr}`,
'[schedule][创建定时任务], 任务ID: %s, cron: %s, 执行命令: %s',
id,
x.schedule,
command,
);
})
}
scheduleStacks.set(id, [
nodeSchedule.scheduleJob(id, schedule, async () => {
Logger.info(`[schedule][准备运行任务] 命令: ${cmdStr}`);
runCron(`ID=${id} ${cmdStr}`);
}),
);
...(extraSchedules?.length
? extraSchedules.map((x) =>
nodeSchedule.scheduleJob(id, x.schedule, async () => {
Logger.info(`[schedule][准备运行任务] 命令: ${cmdStr}`);
runCron(`ID=${id} ${cmdStr}`);
}),
)
: []),
]);
}
callback(null, null);