""" 定时任务 - 清理过期数据 """ import asyncio from datetime import timedelta from app.core.logger import logger from app.database import SessionLocal from app.models.api_nonce import APINonce from app.utils.timezone import beijing_now_naive async def cleanup_expired_nonces_task(): """定时清理过期的 API Nonce 数据""" while True: try: db = SessionLocal() try: # 删除已过期的 nonce(比过期时间早5分钟的数据) expire_threshold = beijing_now_naive() - timedelta(minutes=5) result = db.query(APINonce).filter( APINonce.expires_at < expire_threshold ).delete() db.commit() if result > 0: logger.info(f"[Cleanup] 已清理 {result} 条过期的 api_nonces 记录") finally: db.close() except Exception as e: logger.exception(f"[Cleanup] 清理 api_nonces 失败: {e}") try: db.rollback() except Exception: pass # 每小时执行一次 await asyncio.sleep(3600) def start_cleanup_tasks(): """启动所有定时清理任务""" loop = asyncio.new_event_loop() asyncio.set_event_loop(loop) # 启动 Nonce 清理任务 loop.create_task(cleanup_expired_nonces_task()) # 在后台线程中运行事件循环 import threading thread = threading.Thread(target=loop.run_forever, daemon=True) thread.start() logger.info("[Cleanup] 定时清理任务已启动")