Python Glossary Русский

Python 3.4+Async programmingterm

asyncio.Task

tasks

A task is a coroutine scheduled on the event loop to run concurrently with others. It is created by asyncio.create_task() and can be awaited, cancelled and named.

Syntax

task = asyncio.create_task(coro, name=None); result = await task

The loop keeps only weak references to tasks: a task nobody stored in a variable or a set can be garbage-collected mid-flight. cancel() does not stop a task at once; it raises CancelledError at the task's current await. Do not swallow it — since 3.8 it derives from BaseException, so except Exception lets it through, but a bare except catches it. Never instantiate asyncio.Task(...) directly.

Examples

import asyncio
async def work():
    await asyncio.sleep(0.01)
    return 'ok'
async def main():
    task = asyncio.create_task(work(), name='worker')
    print(task.get_name(), task.done())  # → worker False
    print(await task, task.done())  # → ok True
asyncio.run(main())
import asyncio
async def forever():
    try:
        await asyncio.sleep(10)
    except asyncio.CancelledError:
        print('отменили во время sleep')  # → отменили во время sleep
        raise
async def main():
    task = asyncio.create_task(forever())
    await asyncio.sleep(0.01)
    task.cancel()
    try:
        await task
    except asyncio.CancelledError:
        print(task.cancelled())  # → True
asyncio.run(main())

See also

Open in the full glossarydocs.python.orgReport an inaccuracy