Files
item_bank/app/services/startup.py
T
2026-08-01 16:50:55 +08:00

39 lines
1.1 KiB
Python

"""启动时的清理工作。"""
import logging
from sqlalchemy import update
from app.db import SessionLocal
from app.models.job import JobStatus, ProcessingJob
logger = logging.getLogger(__name__)
# 进程重启后不可能再继续的中间状态
_STALE_STATUSES = (
JobStatus.pending,
JobStatus.ocr_running,
JobStatus.ai_running,
)
async def fail_stale_jobs() -> int:
"""把残留的进行中任务标记为失败。
任务跑在 BackgroundTasks 里,进程重启就没了。不清理的话这些任务会永远
停在 pending/*_running,前端会一直轮询下去。
"""
async with SessionLocal() as db:
result = await db.execute(
update(ProcessingJob)
.where(ProcessingJob.status.in_(_STALE_STATUSES))
.values(
status=JobStatus.failed,
error_message="服务重启,任务中断,请重新上传",
)
)
await db.commit()
count = result.rowcount or 0
if count:
logger.info("已清理 %d 个残留任务", count)
return count