From a7676f527f4790a2bcc6c40dae20a4fb30253176 Mon Sep 17 00:00:00 2001 From: coolxll Date: Sun, 29 Mar 2026 11:42:16 +0800 Subject: [PATCH] feat: add graceful shutdown with signal handler - Add SIGINT/SIGTERM signal handler for graceful exit - Cancel all running tasks on shutdown - Reduce default HTTP timeout from 30s to 10s for faster Ctrl+C response - Support double Ctrl+C for forced exit --- src/core/http_client.py | 2 +- src/web/app.py | 29 +++++++++++++++++++++++++++++ 2 files changed, 30 insertions(+), 1 deletion(-) diff --git a/src/core/http_client.py b/src/core/http_client.py index f3dd8763..a07b8e4b 100644 --- a/src/core/http_client.py +++ b/src/core/http_client.py @@ -22,7 +22,7 @@ @dataclass class RequestConfig: """HTTP 请求配置""" - timeout: int = 30 + timeout: int = 10 # 降低默认超时,让 Ctrl+C 响应更快 max_retries: int = 3 retry_delay: float = 1.0 impersonate: str = "chrome" diff --git a/src/web/app.py b/src/web/app.py index 73408f7d..1e4abb78 100644 --- a/src/web/app.py +++ b/src/web/app.py @@ -5,6 +5,7 @@ import logging import sys +import signal import secrets import hmac import hashlib @@ -26,6 +27,34 @@ logger = logging.getLogger(__name__) +# 优雅退出标志 +_shutdown_requested = False + + +def _signal_handler(signum, frame): + """信号处理器:Ctrl+C 时优雅退出""" + global _shutdown_requested + if _shutdown_requested: + logger.warning("收到第二次退出信号,强制退出") + sys.exit(1) + + _shutdown_requested = True + logger.info("收到退出信号,正在关闭...") + + # 取消所有运行中的任务 + from .task_manager import _task_cancelled + for task_uuid in list(_task_cancelled.keys()): + task_manager.cancel_task(task_uuid) + + logger.info("已取消所有运行中的任务") + sys.exit(0) + + +# 注册信号处理器 +signal.signal(signal.SIGINT, _signal_handler) +if hasattr(signal, "SIGTERM"): + signal.signal(signal.SIGTERM, _signal_handler) + # 获取项目根目录 # PyInstaller 打包后静态资源在 sys._MEIPASS,开发时在源码根目录 if getattr(sys, 'frozen', False):