cleanup.py 1.6 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051
  1. """
  2. 定时任务 - 清理过期数据
  3. """
  4. import asyncio
  5. from datetime import timedelta
  6. from app.core.logger import logger
  7. from app.database import SessionLocal
  8. from app.models.api_nonce import APINonce
  9. from app.utils.timezone import beijing_now_naive
  10. async def cleanup_expired_nonces_task():
  11. """定时清理过期的 API Nonce 数据"""
  12. while True:
  13. try:
  14. db = SessionLocal()
  15. try:
  16. # 删除已过期的 nonce(比过期时间早5分钟的数据)
  17. expire_threshold = beijing_now_naive() - timedelta(minutes=5)
  18. result = db.query(APINonce).filter(
  19. APINonce.expires_at < expire_threshold
  20. ).delete()
  21. db.commit()
  22. if result > 0:
  23. logger.info(f"[Cleanup] 已清理 {result} 条过期的 api_nonces 记录")
  24. finally:
  25. db.close()
  26. except Exception as e:
  27. logger.exception(f"[Cleanup] 清理 api_nonces 失败: {e}")
  28. try:
  29. db.rollback()
  30. except Exception:
  31. pass
  32. # 每小时执行一次
  33. await asyncio.sleep(3600)
  34. def start_cleanup_tasks():
  35. """启动所有定时清理任务"""
  36. loop = asyncio.new_event_loop()
  37. asyncio.set_event_loop(loop)
  38. # 启动 Nonce 清理任务
  39. loop.create_task(cleanup_expired_nonces_task())
  40. # 在后台线程中运行事件循环
  41. import threading
  42. thread = threading.Thread(target=loop.run_forever, daemon=True)
  43. thread.start()
  44. logger.info("[Cleanup] 定时清理任务已启动")