sse-starlette
sse-starlette copied to clipboard
What's the propper way to kill all ongoing generators?
In docs there is the warning about the need to stop all running generators that may result in: "Waiting for background tasks to complete. (CTRL+C to force quit).", and using FastAPI I got "Waiting for connections to close. (CTRL+C to force quit)"
I looked at #8 that appears to be related, but the solution is to press Ctrl+C again?
So, what's the proper way to kill ongoing generators?
In my dev env, uvicorn won't reload unless the client disconnects, and in production a SIGTERM won't kill the process.
I tried a variation from https://stackoverflow.com/a/59089890 cited on #8 without success (captured Ctrl+C and never finishes):
async def shutdown(s: signal):
"""
try to shut down gracefully
"""
print(f"Received exit signal {s.name}...", )
tasks = [t for t in asyncio.all_tasks() if t is not asyncio.current_task() and t.get_name() == "sse_starlette.sse.EventSourceResponse.__call__.<locals>.wrap"]
[task.cancel() for task in tasks]
await asyncio.gather(*tasks)
loop = asyncio.get_event_loop()
signals = (signal.SIGHUP, signal.SIGTERM, signal.SIGINT)
for s in signals:
loop.add_signal_handler(
s, lambda _=s: asyncio.create_task(shutdown(_))
)