diff --git a/back/shared/runCron.ts b/back/shared/runCron.ts index 29ed97e2..72b6e646 100644 --- a/back/shared/runCron.ts +++ b/back/shared/runCron.ts @@ -2,10 +2,39 @@ import { spawn } from 'cross-spawn'; import taskLimit from './pLimit'; import Logger from '../loaders/logger'; import { ICron } from '../protos/cron'; +import { CrontabModel, CrontabStatus } from '../data/cron'; +import { killTask } from '../config/util'; export function runCron(cmd: string, cron: ICron): Promise { return taskLimit.runWithCronLimit(cron, () => { return new Promise(async (resolve: any) => { + // Check if the cron is already running and stop it + try { + const existingCron = await CrontabModel.findOne({ + where: { id: Number(cron.id) }, + }); + if ( + existingCron && + existingCron.pid && + (existingCron.status === CrontabStatus.running || + existingCron.status === CrontabStatus.queued) + ) { + Logger.info( + `[schedule][停止已运行任务] 任务ID: ${cron.id}, PID: ${existingCron.pid}`, + ); + await killTask(existingCron.pid); + // Update the status to idle after killing + await CrontabModel.update( + { status: CrontabStatus.idle, pid: undefined }, + { where: { id: Number(cron.id) } }, + ); + } + } catch (error) { + Logger.error( + `[schedule][检查已运行任务失败] 任务ID: ${cron.id}, 错误: ${error}`, + ); + } + Logger.info( `[schedule][开始执行任务] 参数 ${JSON.stringify({ ...cron,