from fastapi import FastAPI from apscheduler.schedulers.background import BackgroundScheduler from apscheduler.triggers.cron import CronTrigger from app.database import init_db, cleanup_old_cache_entries from app.config import CLEANUP_CRON, CACHE_EXPIRY_HOURS from app.routes import health, browser, cache # Create FastAPI app app = FastAPI() # Include routers app.include_router(health.router) app.include_router(browser.router) app.include_router(cache.router) # Initialize scheduler for periodic cache cleanup scheduler = BackgroundScheduler() scheduler.add_job( cleanup_old_cache_entries, CronTrigger.from_crontab(CLEANUP_CRON), id='cache_cleanup_job', replace_existing=True ) # Initialize database on startup init_db() # Start the scheduler when the application starts @app.on_event("startup") def start_scheduler(): scheduler.start() print(f"Cache cleanup scheduler started with cron: {CLEANUP_CRON}") print(f"Cache entries will expire after {CACHE_EXPIRY_HOURS} hours") # Shutdown the scheduler when the application stops @app.on_event("shutdown") def shutdown_scheduler(): scheduler.shutdown(wait=False) print("Cache cleanup scheduler stopped")