Python 3.7 - asyncio.sleep() and time.sleep() Python 3.7 - asyncio.sleep() and time.sleep() python-3.x python-3.x

Python 3.7 - asyncio.sleep() and time.sleep()


You aren't seeing anything special because there's nothing much asynchronous work in your code. However, the main difference is that time.sleep(5) is blocking, and asyncio.sleep(5) is non-blocking.

When time.sleep(5) is called, it will block the entire execution of the script and it will be put on hold, just frozen, doing nothing. But when you call await asyncio.sleep(5), it will ask the event loop to run something else while your await statement finishes its execution.

Here's an improved example.

import asyncioasync def hello():    print('Hello ...')    await asyncio.sleep(5)    print('... World!')async def main():    await asyncio.gather(hello(), hello())asyncio.run(main())

Will output:

~$ python3.7 async.pyHello ...Hello ...... World!... World!

You can see that await asyncio.sleep(5) is not blocking the execution of the script.

Hope it helps :)