import os import shutil import threading import time import logging UPLOAD_FOLDER = 'temp_files' CLEANUP_INTERVAL = 3600 # 清理临时文件的间隔(秒) FILE_EXPIRY = 7200 # 文件过期时间(秒) file_registry = {} file_lock = threading.Lock() def cleanup_temp_files(): current_time = time.time() expired_folders = [] for folder_name in os.listdir(UPLOAD_FOLDER): folder_path = os.path.join(UPLOAD_FOLDER, folder_name) if not os.path.isdir(folder_path): continue try: folder_mtime = os.path.getmtime(folder_path) if current_time - folder_mtime > FILE_EXPIRY: expired_folders.append(folder_path) logging.info(f"检测到过期文件夹: {folder_path} (修改时间: {time.ctime(folder_mtime)})") except Exception as e: logging.error(f"获取文件夹 {folder_path} 信息失败: {e}") for folder_path in expired_folders: try: shutil.rmtree(folder_path) logging.info(f"已删除过期文件夹: {folder_path}") except Exception as e: logging.error(f"删除文件夹 {folder_path} 失败: {e}") logging.info(f"清理完成,共删除 {len(expired_folders)} 个过期文件夹") def start_cleanup_thread(): def cleanup_loop(): while True: logging.info("开始执行定期清理任务...") cleanup_temp_files() time.sleep(CLEANUP_INTERVAL) thread = threading.Thread(target=cleanup_loop) thread.daemon = True thread.start() logging.info("已启动后台清理线程")