japi/apps/jfile/file_cleaner.py
jingrow c99e20ff61 优化jfile服务:将清理间隔改为可配置,文件保留时间调整为15分钟
- 将清理间隔从硬编码3600秒改为可配置项cleanup_interval_seconds
- 文件保留时间从1小时调整为15分钟(0.25小时)
- 清理间隔同步调整为15分钟(900秒),保持与保留时间一致
- 优化存储空间使用,过期文件更及时清理
2025-11-21 08:50:53 +08:00

34 lines
1.3 KiB
Python

import os
import asyncio
from datetime import datetime, timedelta
class FileCleaner:
def __init__(self, target_dir, retention_hours, cleanup_interval_seconds=3600):
self.target_dir = target_dir
self.retention_hours = retention_hours
self.cleanup_interval_seconds = cleanup_interval_seconds
async def periodic_cleanup(self):
while True:
try:
self.cleanup_old_files()
except Exception as e:
print(f"清理文件时出错: {str(e)}")
await asyncio.sleep(self.cleanup_interval_seconds)
def cleanup_old_files(self):
if not os.path.exists(self.target_dir):
return
cutoff_time = datetime.now() - timedelta(hours=self.retention_hours)
for filename in os.listdir(self.target_dir):
file_path = os.path.join(self.target_dir, filename)
# 跳过目录
if os.path.isdir(file_path):
continue
file_time = datetime.fromtimestamp(os.path.getctime(file_path))
if file_time < cutoff_time:
try:
os.remove(file_path)
print(f"已删除过期文件: {filename}")
except Exception as e:
print(f"删除文件失败 {filename}: {str(e)}")