"""定期清理任务 — Celery Beat 调度。 包含: - cleanup_stale_pending_tasks: 定期清理卡在 pending 超时的 generation_tasks """ import logging from celery import shared_task from worker_app.tasks._startup import ( PENDING_TASK_TIMEOUT_MINUTES, cleanup_stale_pending_tasks, ) logger = logging.getLogger(__name__) @shared_task(name="worker.cleanup_stale_pending_tasks") def scheduled_cleanup_stale_pending(timeout_minutes: int = PENDING_TASK_TIMEOUT_MINUTES) -> dict: """Celery Beat 调度的定期任务:清理超时的 pending 任务。 每 10 分钟执行一次(由 celery_app.py 的 beat_schedule 配置), 查找所有 status='pending' 且 created_at < NOW() - timeout_minutes 的 generation_tasks,批量更新为 failed。 Args: timeout_minutes: 超时时间(分钟),默认 30 分钟 Returns: {"cleaned": int} """ count = cleanup_stale_pending_tasks(timeout_minutes) if count > 0: logger.info("[Beat] 清理了 %d 个超时 pending 任务(超时阈值 %d 分钟)", count, timeout_minutes) return {"cleaned": count}