Description
Is it possible to use BackgroundTasks with websockets?
I tried with a simple case:
def test():
print('test')
@router.post("/test")
async def send_notification(background_tasks: BackgroundTasks):
background_tasks.add_task(test)
return {"message": "Notification sent in the background"}
@router.websocket("/ws")
async def listen(websocket: WebSocket, background_tasks: BackgroundTasks):
await websocket.accept()
background_tasks.add_task(test)
The send_notification
http endpoint example works, but the listen
websocket endpoint doesn't.
Thanks!
Background tasks internally depend on a Request
, and they are executed after returning the request to the client. In the case of a WebSocket, as the WebSocket is not really "finished" but is an ongoing connection, it wouldn't be a background task.
Nevertheless, you can make sure an async function is executed with asyncio.ensure_future
: https://docs.python.org/3/library/asyncio-future.html#asyncio.ensure_future
Okay, got it, thanks.
Cool! I'll close this issue now then.
Most helpful comment
Background tasks internally depend on a
Request
, and they are executed after returning the request to the client. In the case of a WebSocket, as the WebSocket is not really "finished" but is an ongoing connection, it wouldn't be a background task.Nevertheless, you can make sure an async function is executed with
asyncio.ensure_future
: https://docs.python.org/3/library/asyncio-future.html#asyncio.ensure_future