如何在Flask中定期删除Celery(MongoDB后端)数据及Flower日志?
定期清理Celery MongoDB后端数据与Flower日志
一、清理Celery MongoDB后端数据
Celery用MongoDB作为后端时,默认会把任务元数据存在celery_taskmeta和celery_groupmeta两个集合里。要清理48小时前的数据,有两种常用方式:
1. 用Mongo Shell直接执行
登录MongoDB shell,切换到Celery对应的数据库,执行删除命令:
// 计算48小时前的时间戳 var cutoff = new Date(Date.now() - 48*60*60*1000); // 清理单个任务元数据 db.celery_taskmeta.deleteMany({"date_done": {"$lt": cutoff}}); // 清理组任务元数据 db.celery_groupmeta.deleteMany({"date_done": {"$lt": cutoff}});
如果你的Celery自定义了集合名称,记得替换上面的集合名。
2. 用Python脚本(适合整合到项目)
写个简单的Python脚本,用pymongo连接数据库执行清理:
from pymongo import MongoClient from datetime import datetime, timedelta # 替换为你的MongoDB连接地址和Celery数据库名 client = MongoClient('mongodb://localhost:27017/') db = client['celery'] # 计算48小时前的时间节点 cutoff_time = datetime.now() - timedelta(hours=48) # 执行清理 db.celery_taskmeta.delete_many({"date_done": {"$lt": cutoff_time}}) db.celery_groupmeta.delete_many({"date_done": {"$lt": cutoff_time}}) client.close()
二、清理Flower日志
Flower的日志分两种存储方式,对应不同的清理方法:
1. 文件日志清理
如果Flower用文件存储日志(默认或通过--log-file指定路径),可以用两种方式:
- logrotate(推荐):在Linux系统下创建logrotate配置文件
/etc/logrotate.d/flower,内容如下(替换日志文件路径):
/path/to/your/flower.log { daily rotate 7 missingok notifempty compress delaycompress copytruncate }
这个配置会每天轮转日志,保留最近7天的日志文件。
- find命令删除旧日志:如果日志是按日期分割的,直接用find命令删除48小时前的文件:
find /path/to/flower/logs -name "flower*.log" -mtime +2 -delete
2. MongoDB存储的Flower日志清理
如果你配置了Flower用MongoDB存储日志(通过--db参数),默认集合是flower_events,清理方式和Celery后端类似:
用Mongo Shell执行:
var cutoff = new Date(Date.now() - 48*60*60*1000); db.flower_events.deleteMany({"timestamp": {"$lt": cutoff}});
或者把这段逻辑加到上面的Python清理脚本里。
三、定时自动执行清理
用Linux的crontab来定时触发清理任务:
- 编辑crontab:
crontab -e - 添加定时规则,比如每天凌晨2点执行清理脚本:
0 2 * * * /usr/bin/python3 /path/to/your/cleanup_script.py
如果直接用Mongo Shell命令,也可以这么写:
0 2 * * * mongo celery --eval 'var cutoff = new Date(Date.now() - 48*60*60*1000); db.celery_taskmeta.deleteMany({"date_done": {"$lt": cutoff}}); db.celery_groupmeta.deleteMany({"date_done": {"$lt": cutoff}}); db.flower_events.deleteMany({"timestamp": {"$lt": cutoff}})'
注意替换MongoDB的数据库名和命令路径。
内容的提问来源于stack exchange,提问作者Harshdeep Kanhai
相关产品推荐
相关产品推荐

