The Sleep() Function Of Asyncio In Python

Overview:

  • The asyncio.sleep() method suspends the execution of a coroutine.

  • Coroutines voluntarily yield CPU leading to co-operative multitasking through the await keyword.

Example:

# Example Python program that uses the asyncio.sleep()
# to yield CPU from a coroutine
import asyncio

# Coroutine that prints odd numbers
async def printOdd():
    for i in range(1,10, 2):
        print(i)
        await asyncio.sleep(0)

# Coroutine that prints even numbers
async def printEven():
    for i in range(2,10, 2):
        print(i)
        await asyncio.sleep(0)

# Coroutine that awaits on tasks printOdd and printEven
async def main():
    oddTask  = asyncio.create_task(printOdd())
    evenTask = asyncio.create_task(printEven())

    await asyncio.wait([oddTask, evenTask])

# Create a new event loop and run the tasks
l = asyncio.new_event_loop()
asyncio.set_event_loop(l)
asyncio.run(main())

Output:

1

2

3

4

5

6

7

8

9


Copyright 2023 © pythontic.com