0

here is the code:

In [168]: async def myTask():
     ...:     await asyncio.sleep(2)
     ...:     print("processing task")

In [168]: async def generator():
     ...:     for i in range(5):
     ...:         asyncio.create_task(myTask())

In [168]: def abcd():
     ...:     t0=time.time()
     ...:     loop=asyncio.get_event_loop()
     ...:     loop.run_until_complete(generator())
     ...:     t1=time.time()
     ...:     print(t1-t0)

Ideally calling abc() should sleep for around 10 seconds(as I have not awaited the asyncio.create_task(myTask())), but the function is getting completed in less than 0.1 secs.

In [167]: abcd()
processing task
processing task
processing task
processing task
processing task
0.0004038810729980469
7
  • 1
    You haven't awaited myTask(). If you try replacing myTask() with asyncio.sleep(2) directly, you'll get exactly the same behavior. Hmmm... Commented Jan 7, 2020 at 0:02
  • @MateenUlhaq Yes, but in this case, no output should be printed. It's confusing. Commented Jan 7, 2020 at 0:07
  • Did you save the file beforehand? Try it again with the sample you posted. It seems to generate no additional output for me. Commented Jan 7, 2020 at 0:09
  • @MateenUlhaq I am running it in python jupyter notebook Commented Jan 7, 2020 at 0:10
  • repl.it/repls/CylindricalSilkyLaboratory Commented Jan 7, 2020 at 0:10

1 Answer 1

2

If you try the following code, you will get output after around 2 seconds. Well, but we haven't awaited any tasks. The reason is that the Jupyter notebook itself is running in an event loop. So when you use the default event loop, it actually points to the Jupyter notebook's event loop.

import asyncio

async def myTask():
    await asyncio.sleep(2)
    print("processing task")

for i in range(5):
    asyncio.create_task(myTask())
Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.