The sleep() function of asyncio in Python

The sleep function of Python asyncio module suspends a coroutine for a specified number of seconds.

Asyncio Updated 17 May 2022 1 min read

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

python
# 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

Output
1

2

3

4

5

6

7

8

9