Fix preview platform switching, add stale task cleanup on startup

This commit is contained in:
Yuzhiran Dev
2026-05-18 23:38:30 +08:00
parent 7b4e52743b
commit 671cec58fa
2 changed files with 29 additions and 0 deletions
+25
View File
@@ -48,6 +48,31 @@ Base.metadata.create_all(bind=engine)
init_db()
import_initial_data()
# 清理超时任务(运行超过 1 小时的任务视为故障)
from datetime import datetime, timezone, timedelta
from .database import SessionLocal
from .models import ContentTask
try:
cleanup_db = SessionLocal()
cutoff = datetime.now(timezone.utc) - timedelta(hours=1)
stale = cleanup_db.query(ContentTask).filter(
ContentTask.status == "running",
ContentTask.started_at.isnot(None),
ContentTask.started_at < cutoff
).all()
for t in stale:
t.status = "failed"
t.error_msg = "任务超时(服务重启导致状态丢失)"
if t.started_at:
t.duration = int((datetime.now(timezone.utc) - t.started_at).total_seconds())
logger.warning(f"标记超时任务: {t.task_id}")
if stale:
cleanup_db.commit()
logger.info(f"已清理 {len(stale)} 个超时任务")
cleanup_db.close()
except Exception as e:
logger.warning(f"任务清理失败: {e}")
# 注册 API 路由
app.include_router(topics.router)
app.include_router(system.router)