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)}")