Skip to content

Commit 58a2639

Browse files
add scheduler calculations to background task
1 parent 878f4e2 commit 58a2639

File tree

1 file changed

+15
-8
lines changed

1 file changed

+15
-8
lines changed

src/main.py

Lines changed: 15 additions & 8 deletions
Original file line numberDiff line numberDiff line change
@@ -1,4 +1,5 @@
11
import logging
2+
import asyncio
23
from contextlib import asynccontextmanager
34

45
import uvicorn
@@ -49,20 +50,26 @@
4950

5051
prometheus_scheduler = PrometheusScheduler()
5152

53+
@repeat_every(
54+
seconds=prometheus_scheduler.service_config.get("metrics_schedule", 30),
55+
logger=logger,
56+
raise_exceptions=False
57+
)
58+
async def schedule_metrics_calculation():
59+
prometheus_scheduler.calculate()
5260

5361
@asynccontextmanager
5462
async def lifespan(app: FastAPI):
55-
56-
@repeat_every(
57-
seconds=prometheus_scheduler.service_config.get("metrics_schedule", 30)
58-
)
59-
async def schedule_metrics_calculation():
60-
prometheus_scheduler.calculate()
61-
62-
await schedule_metrics_calculation()
63+
task = asyncio.create_task(schedule_metrics_calculation())
6364

6465
yield
6566

67+
task.cancel()
68+
try:
69+
await task
70+
except asyncio.CancelledError:
71+
logger.info("Prometheus metrics calculation task cancelled during shutdown")
72+
6673

6774
app = FastAPI(
6875
title="TrustyAI Service API",

0 commit comments

Comments
 (0)