From 1124040eebafac730db653010a57f858bd3f9107 Mon Sep 17 00:00:00 2001 From: "copilot-swe-agent[bot]" <198982749+Copilot@users.noreply.github.com> Date: Mon, 22 Dec 2025 14:46:15 +0000 Subject: [PATCH] Optimize PID validation and use bulk database update Co-authored-by: whyour <22700758+whyour@users.noreply.github.com> --- back/config/util.ts | 5 +++++ back/loaders/initData.ts | 11 +++++++++-- 2 files changed, 14 insertions(+), 2 deletions(-) diff --git a/back/config/util.ts b/back/config/util.ts index e80ab284..47b7b183 100644 --- a/back/config/util.ts +++ b/back/config/util.ts @@ -398,6 +398,11 @@ export function psTree(pid: number): Promise { } export function isPidRunning(pid: number): boolean { + // Validate PID is a positive integer + if (!pid || pid <= 0 || !Number.isInteger(pid)) { + return false; + } + try { // Signal 0 doesn't kill the process, just checks if it exists process.kill(pid, 0); diff --git a/back/loaders/initData.ts b/back/loaders/initData.ts index 06968765..8fbe3b08 100644 --- a/back/loaders/initData.ts +++ b/back/loaders/initData.ts @@ -134,16 +134,23 @@ export default async () => { // 初始化更新所有任务状态为空闲 // 但保留仍在运行的任务的状态 const allCrons = await CrontabModel.findAll({ raw: true }); + const idsToReset: number[] = []; + for (const cron of allCrons) { // 如果任务有 PID 且进程仍在运行,则保持其状态 if (cron.pid && isPidRunning(cron.pid)) { // 保留当前状态(running 或 queued) continue; } - // 否则将状态重置为 idle,并清除 PID + // 收集需要重置的任务 ID + idsToReset.push(cron.id!); + } + + // 批量更新所有需要重置的任务 + if (idsToReset.length > 0) { await CrontabModel.update( { status: CrontabStatus.idle, pid: undefined }, - { where: { id: cron.id } } + { where: { id: { [Op.in]: idsToReset } } } ); }