Refactor periodic tasks to use injected scheduler resources

This commit is contained in:
2026-04-11 20:32:36 +02:00
parent 9cba5a9fcb
commit ae81a8f5be
10 changed files with 122 additions and 94 deletions

View File

@@ -20,6 +20,7 @@ from app.utils.runtime_state import get_effective_settings
if TYPE_CHECKING:
import aiosqlite
from app.config import Settings
from app.services import geo_service
if TYPE_CHECKING:
@@ -34,23 +35,18 @@ GEO_FLUSH_INTERVAL: int = 60
JOB_ID: str = "geo_cache_flush"
async def _get_db(app: Any) -> tuple[aiosqlite.Connection, bool]:
settings = get_effective_settings(app)
async def _get_db(settings: "Settings") -> tuple[aiosqlite.Connection, bool]:
db = await open_db(settings.database_path)
return db, True
async def _run_flush(app: Any) -> None:
async def _run_flush_with_settings(settings: "Settings") -> None:
"""Flush the geo service dirty set to the application database.
Reads shared resources from ``app.state`` and delegates to
:func:`~app.services.geo_service.flush_dirty`.
Args:
app: The :class:`fastapi.FastAPI` application instance passed via
APScheduler ``kwargs``.
settings: The resolved application settings used for database access.
"""
db, close_db = await _get_db(app)
db, close_db = await _get_db(settings)
try:
count = await geo_service.flush_dirty(db)
finally:
@@ -61,6 +57,10 @@ async def _run_flush(app: Any) -> None:
log.debug("geo_cache_flush_ran", flushed=count)
async def _run_flush(app: FastAPI) -> None:
await _run_flush_with_settings(get_effective_settings(app))
def register(app: FastAPI) -> None:
"""Add (or replace) the geo cache flush job in the application scheduler.
@@ -71,11 +71,12 @@ def register(app: FastAPI) -> None:
app: The :class:`fastapi.FastAPI` application instance whose
``app.state.scheduler`` will receive the job.
"""
settings = get_effective_settings(app)
app.state.scheduler.add_job(
_run_flush,
_run_flush_with_settings,
trigger="interval",
seconds=GEO_FLUSH_INTERVAL,
kwargs={"app": app},
kwargs={"settings": settings},
id=JOB_ID,
replace_existing=True,
)