task_remove.py 1.3 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647
  1. # -*- coding: utf-8 -*-
  2. # Author : Charley
  3. # Python : 3.10.8
  4. # Date : 2025/9/28 11:32
  5. from loguru import logger
  6. from mysql_pool import MySQLConnectionPool
  7. sql_pool = MySQLConnectionPool(log=logger)
  8. def remove_unwanted_tasks_batch():
  9. """
  10. 分批删除cgc_task表中cert_id末尾三位数不在1-300范围内的记录
  11. """
  12. try:
  13. deleted_total = 0
  14. batch_size = 10000 # 每批删除10000条记录
  15. while True:
  16. # 使用原生SQL执行分批删除
  17. delete_query = """
  18. DELETE FROM cgc_task
  19. WHERE CAST(RIGHT(cert_id, 3) AS UNSIGNED) NOT BETWEEN 1 AND 300
  20. LIMIT %s
  21. """
  22. # 执行删除操作
  23. cursor = sql_pool._execute(delete_query, (batch_size,), commit=True)
  24. affected_rows = cursor.rowcount
  25. deleted_total += affected_rows
  26. logger.info(f"已删除 {affected_rows} 条记录,总计: {deleted_total}")
  27. # 如果本次删除少于批次大小,说明已处理完
  28. if affected_rows < batch_size:
  29. break
  30. logger.success(f"删除完成,总共删除 {deleted_total} 条记录")
  31. except Exception as e:
  32. logger.error(f"批量删除失败: {e}")
  33. # 执行清理任务
  34. if __name__ == "__main__":
  35. remove_unwanted_tasks_batch()