From 02fa5b1703bdb2805263aef952b273f77700f4ca Mon Sep 17 00:00:00 2001 From: "copilot-swe-agent[bot]" <198982749+Copilot@users.noreply.github.com> Date: Mon, 17 Nov 2025 12:33:16 +0000 Subject: [PATCH] Stop running tasks before starting new scheduled instance Co-authored-by: whyour <22700758+whyour@users.noreply.github.com> --- back/shared/runCron.ts | 29 +++++++++++++++++++++++++++++ 1 file changed, 29 insertions(+) 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,