Commit b45c55be by 江名洋

feat(scheduler): Enhance shutdown handling and task execution

- Added signal handlers for graceful shutdown in the FastAPI lifespan.
- Updated SchedulerManager to check for shutdown requests before executing tasks.
- Refactored task execution to run in daemon threads for improved responsiveness.
- Adjusted timeout settings for scheduler shutdown to ensure timely application exit.
1 parent 616e411a
Showing 152 changed files with 33 additions and 3 deletions
......@@ -106,7 +106,6 @@ class SchedulerManager:
"""策略效果分析定时任务"""
logger.info(f"[Scheduler] Start sync_strategy_analysis at {datetime.now()}")
try:
import asyncio
from app.services.strategy_service import get_task_state
state = get_task_state()
if state.get("running"):
......@@ -150,7 +149,7 @@ class SchedulerManager:
@classmethod
async def sync_dws_task(cls):
"""DWS 数据加工定时任务:每天凌晨1点执行,日期范围从上月26号到今天"""
"""DWS 数据加工定时任务:每天凌晨1点执行,日期范围从上月26号到当天"""
logger.info(f"[Scheduler] Start sync_dws_task at {datetime.now()}")
try:
today = date.today()
......
......@@ -93,7 +93,6 @@ async def lifespan(app: FastAPI):
# 关闭时执行
print("[*] Stopping Data Analyze WebUI...")
try:
# 强制设置停止超时,防止由于任务阻塞导致进程无法退出
await asyncio.wait_for(SchedulerManager.stop(), timeout=5.0)
except asyncio.TimeoutError:
print("[!] Scheduler stop timed out, forcing exit.")
......@@ -184,6 +183,37 @@ async def health():
if __name__ == "__main__":
import signal
import threading
# Ctrl+C 后若优雅关闭卡住,超时后强制结束本进程(逻辑仅在此入口生效)
FORCE_EXIT_SECONDS = 3
_force_exit_state = {"armed": False}
_force_exit_lock = threading.Lock()
def _arm_force_exit():
with _force_exit_lock:
if _force_exit_state["armed"]:
return
_force_exit_state["armed"] = True
def _force_kill():
time.sleep(FORCE_EXIT_SECONDS)
print(f"[!] {FORCE_EXIT_SECONDS}s 内未能正常退出,强制结束进程。")
os._exit(1)
threading.Thread(target=_force_kill, daemon=True, name="force-exit").start()
def _on_exit_signal(signum, _frame):
label = "Ctrl+C" if signum == signal.SIGINT else f"signal {signum}"
print(f"[*] 收到退出信号 ({label}),正在关闭服务...")
_arm_force_exit()
raise KeyboardInterrupt
signal.signal(signal.SIGINT, _on_exit_signal)
if hasattr(signal, "SIGTERM"):
signal.signal(signal.SIGTERM, _on_exit_signal)
# 端口指定 9500,root_path 适配子路径部署(如 /daw)
uvicorn.run(
"main:app",
......@@ -191,4 +221,5 @@ if __name__ == "__main__":
port=9500,
reload=settings.APP_DEBUG,
root_path=settings.ROOT_PATH or "",
timeout_graceful_shutdown=FORCE_EXIT_SECONDS,
)
No preview for this file type
No preview for this file type
No preview for this file type
No preview for this file type
No preview for this file type
No preview for this file type
No preview for this file type
No preview for this file type
No preview for this file type
No preview for this file type
No preview for this file type
No preview for this file type
No preview for this file type
No preview for this file type
No preview for this file type
No preview for this file type
No preview for this file type
No preview for this file type
No preview for this file type
No preview for this file type
No preview for this file type
Markdown is supported
You are about to add 0 people to the discussion. Proceed with caution.
Finish editing this message first!