Issue
I'm trying to use asyncio lib in the attempt to have my code make 3 HTTP GET/POST requests 'at the same time', in order to have the responses as fast as possible. (Sometimes one or the other request gets delayed, which end up delaying the next one.)
So I went to asyncio docs, and I found this example: https://docs.python.org/3/library/asyncio-task.html#coroutines
import asyncio
import time
async def say_after(delay, what):
await asyncio.sleep(delay)
print(what)
async def main():
print(f"started at {time.strftime('%X')}")
await say_after(1, 'hello')
await say_after(2, 'world')
print(f"finished at {time.strftime('%X')}")
asyncio.run(main())
I actually adapted for myself, but it didn't seem to help at all, just make the code more complex with no upside.
When testing the sample code (above) I assumed if I increased the delay time for the first say_after()
, the second would be printed first:
await say_after(5, 'hello') #5 seconds of sleep before print
await say_after(2, 'world')
However, it didn't. The return was:
started at 16:04:30
hello
world
finished at 16:04:37
So what is the purpose of this asyncio code? I could have the same result with no async:
def say_after_b(delay, what):
time.sleep(delay)
print(what)
def main_b():
print(f"started at {time.strftime('%X')}")
say_after_b(5, 'hello')
say_after_b(2, 'world')
print(f"finished at {time.strftime('%X')}")
main_b()
return:
started at 16:04:37
hello
world
finished at 16:04:44
The way I see it the async code, with the increased time, should have gone like this:
sleep 1 sec > sleep 2 sec > print('world') > sleep 3 sec > sleep 4 sec > sleep 5 sec > print('hello') > End.
Is my assumption wrong?
Solution
Read one extra paragraph in the docs you mentioned.
Above the example code you quote, it clearly says
The following snippet of code will print “hello” after waiting for 1 second, and then print “world” after waiting for another 2 seconds
and the next example is to
run two say_after coroutines concurrently
(hint: you need to create tasks to run coroutines concurrently)
Answered By - Bart Van Loon
0 comments:
Post a Comment
Note: Only a member of this blog may post a comment.