japi/apps/jfile/file_cleaner.py
2025-05-12 02:39:56 +08:00

33 lines
1.2 KiB
Python

import os
import asyncio
from datetime import datetime, timedelta
class FileCleaner:
def __init__(self, target_dir, prefix, retention_hours):
self.target_dir = target_dir
self.prefix = prefix
self.retention_hours = retention_hours
async def periodic_cleanup(self):
while True:
try:
self.cleanup_old_files()
except Exception as e:
print(f"清理文件时出错: {str(e)}")
await asyncio.sleep(3600)
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):
if not filename.startswith(self.prefix):
continue
file_path = os.path.join(self.target_dir, filename)
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)}")