Keyboard shortcuts

Press or to navigate between chapters

Press S or / to search in the book

Press ? to show this help

Press Esc to hide this help

Async sleep in loop

  • create_task

  • 4 sleeping in parallel will be much faster

  • This time we used create_task to set up the tasks ahead of time and the we awaited all of them.

import time
import sys
import asyncio

async def do_task(task_id: int, sec: int):
    print(f"Start {task_id}")
    await asyncio.sleep(sec)
    print(f"End {task_id}")

async def main():
    print("Main started")
    if len(sys.argv) != 2:
        exit(f"Usage {sys.argv[0]} NUMBER")

    co_routines = []
    for i in range(int(sys.argv[1])):
        co_routines.append(do_task(i, 1))

    print("Tasks created")

    for t in co_routines:
        await t

    print("Main ended")

start = time.monotonic()
asyncio.run(main())
end = time.monotonic()
print(f"Elapsed {end-start}")
Main started
Tasks created
Start 0
End 0
Start 1
End 1
Start 2
End 2
Start 3
End 3
Main ended
Elapsed 4.004389520036057