Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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

When I go to the asyncio page, the first example is a hello world program. When I run it on python 3.73, I can't see any different from the normal one, can anyone tell me the difference and give a non-trivial example?

In [1]: import asyncio    ...:    ...: async def main():    ...:     print('Hello ...')    ...:     await asyncio.sleep(5)    ...:     print('... World!')    ...:    ...: # Python 3.7+    ...: asyncio.run(main()) Hello ... ... World!  In [2]:  In [2]: import time    ...:    ...: def main():    ...:     print('Hello ...')    ...:     time.sleep(5)    ...:     print('... World!')    ...:    ...: # Python 3.7+    ...: main() Hello ... ... World! 

I intentionally increase the time from 1s to 5s, hope to see something special but I didn't.

like image 378
an offer can't refuse Avatar asked Jun 24 '19 04:06

an offer can't refuse


People also ask

What is Asyncio sleep ()?

async sleep - if you need pause an entire script (supposed to work concurrently) execution, it is sleep. If you need to pause single coroutine, it is asyncio.sleep.

What is time sleep in Python?

Python time sleep function is used to add delay in the execution of a program. We can use python sleep function to halt the execution of the program for given time in seconds. Notice that python time sleep function actually stops the execution of current thread only, not the whole program.

Is Asyncio sleep in milliseconds?

On Linux asyncio uses the epoll_wait system call, which specifies the timeout in milliseconds, so anything sub-millisecond won't work, despite being able to specify it in asyncio. sleep() .

How many times should Asyncio run () be called?

It should be used as a main entry point for asyncio programs, and should ideally only be called once. New in version 3.7.


1 Answers

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 asyncio  async 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.py Hello ... Hello ... ... World! ... World! 

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

Hope it helps :)

like image 54
Nimeshka Srimal Avatar answered Sep 22 '22 12:09

Nimeshka Srimal