async python

In the context of asyncio, the tasks are typically represented by coroutines or Future objects. A coroutine is a special type of function that can be paused and resumed, allowing for asynchronous execution. A Future is an object that represents the result of an asynchronous operation.

To actually run a coroutine, asyncio provides following mechanisms:

  • asyncio.run()
  • The asyncio.create_task() function to run coroutines concurrently as asyncio Tasks.
  • The asyncio.TaskGroup class provides a more modern alternative to create_task() New in version 3.11
async def main():
    async with asyncio.TaskGroup() as tg:
        task1 = tg.create_task(
            say_after(1, 'hello'))
 
        task2 = tg.create_task(
            say_after(2, 'world'))
 
        print(f"started at {time.strftime('%X')}")
 
    # The await is implicit when the context manager exits.
 
    print(f"finished at {time.strftime('%X')}")