Skip to content

Commit 40f3cc9

Browse files
feat: Ensure background task cancellation in startup_event
1 parent 9ceaf6c commit 40f3cc9

File tree

1 file changed

+6
-5
lines changed

1 file changed

+6
-5
lines changed

src/server/server_utils.py

Lines changed: 6 additions & 5 deletions
Original file line numberDiff line numberDiff line change
@@ -61,11 +61,12 @@ async def lifespan(_: FastAPI) -> AsyncGenerator[None, None]:
6161
"""
6262
task = asyncio.create_task(_remove_old_repositories())
6363

64-
yield # app runs while the background task is alive
65-
66-
task.cancel() # ask the worker to stop
67-
with suppress(asyncio.CancelledError):
68-
await task # swallow the cancellation signal
64+
try:
65+
yield # app runs while the background task is alive
66+
finally:
67+
task.cancel() # ask the worker to stop
68+
with suppress(asyncio.CancelledError):
69+
await task # swallow the cancellation signal
6970

7071

7172
async def _remove_old_repositories(

0 commit comments

Comments
 (0)