# Background tasks
# Creating Tasks
It is often desirable and very convenient to make usage of tasks (opens new window) in async Python. Sanic provides a convenient method to add tasks to the currently running loop. It is somewhat similar to
asyncio.create_task. For adding tasks before the 'App' loop is running, see next section.
async def notify_server_started_after_five_seconds(): await asyncio.sleep(5) print('Server successfully started!') app.add_task(notify_server_started_after_five_seconds())
Sanic will attempt to automatically inject the app, passing it as an argument to the task.
async def auto_inject(app): await asyncio.sleep(5) print(app.name) app.add_task(auto_inject)
Or you can pass the
app argument explicitly.
async def explicit_inject(app): await asyncio.sleep(5) print(app.name) app.add_task(explicit_inject(app))
# Adding tasks before
It is possible to add background tasks before the App is run ie. before
app.run. To add a task before the App is run, it is recommended to not pass the coroutine object (ie. one created by calling the
async callable), but instead just pass the callable and Sanic will create the coroutine object on each worker. Note: the tasks that are added such are run as
before_server_start jobs and thus run on every worker (and not in the main process). This has certain consequences, please read this comment (opens new window) on this issue (opens new window) for further details.
To add work on the main process, consider adding work to
@app.main_process_start. Note: the workers won't start until this work is completed.
Example to add a task before
async def slow_work(...): ... app = Sanic(...) app.add_task(slow_work) # Note: we are passing the callable and not coroutine object `slow_work(...)` app.run(...)
To pass parameters to
functools.partial can be used.