import shutil import time import os from pathlib import Path from apscheduler.schedulers.background import BackgroundScheduler TEMP_DIR = Path("backend/temp_uploads") def init_temp_dir(): """임시 디렉토리 생성 (없으면 생성)""" if not TEMP_DIR.exists(): TEMP_DIR.mkdir(parents=True, exist_ok=True) print(f"Created temp directory at: {TEMP_DIR.absolute()}") def cleanup_old_files(max_age_seconds: int = 600): """지정된 시간(기본 10분)보다 오래된 파일/폴더 삭제""" if not TEMP_DIR.exists(): return now = time.time() deleted_count = 0 for item in TEMP_DIR.iterdir(): try: # 최종 수정 시간 확인 item_mtime = item.stat().st_mtime if now - item_mtime > max_age_seconds: if item.is_dir(): shutil.rmtree(item) else: item.unlink() deleted_count += 1 except Exception as e: print(f"Error deleting {item}: {e}") if deleted_count > 0: print(f"Cleaned up {deleted_count} old items from temp directory.") def cleanup_all(): """서버 시작 시 모든 임시 파일 삭제""" if TEMP_DIR.exists(): shutil.rmtree(TEMP_DIR) init_temp_dir() print("Cleaned up all temporary files on startup.") def start_scheduler(): """백그라운드 스케줄러 시작 (1분마다 정리 작업 실행)""" scheduler = BackgroundScheduler() # 10분(600초) 지난 파일 삭제 작업을 1분마다 수행 scheduler.add_job(cleanup_old_files, 'interval', minutes=1, args=[600]) scheduler.start() return scheduler