From f74cce164e2065a866bf6d89e53fa5a4b4840cf2 Mon Sep 17 00:00:00 2001 From: pgjones Date: Sat, 17 Apr 2021 11:49:24 +0100 Subject: [PATCH] Update documentation on asyncio background tasks This has been an early question from users, so best to explain. --- docs/async-await.rst | 17 +++++++++++++++++ docs/deploying/asgi.rst | 2 ++ 2 files changed, 19 insertions(+) diff --git a/docs/async-await.rst b/docs/async-await.rst index c8981f88..3fc24a06 100644 --- a/docs/async-await.rst +++ b/docs/async-await.rst @@ -39,6 +39,23 @@ most use cases, but Flask's async support enables writing and using code that wasn't possible natively before. +Background tasks +---------------- + +Async functions will run in an event loop until they complete, at +which stage the event loop will stop. This means any additional +spawned tasks that haven't completed when the async function completes +will be cancelled. Therefore you cannot spawn background tasks, for +example via ``asyncio.create_task``. + +If you wish to use background tasks it is best to use a task queue to +trigger background work, rather than spawn tasks in a view +function. With that in mind you can spawn asyncio tasks by serving +Flask with a ASGI server and utilising the asgiref WsgiToAsgi adapter +as described in :ref:`asgi`. This works as the adapter creates an +event loop that runs continually. + + When to use Quart instead ------------------------- diff --git a/docs/deploying/asgi.rst b/docs/deploying/asgi.rst index 6e70fee7..c7e04027 100644 --- a/docs/deploying/asgi.rst +++ b/docs/deploying/asgi.rst @@ -1,3 +1,5 @@ +.. _asgi: + ASGI ====