When I run code:
import asyncio
async def foo(text):
print(text)
await asyncio.sleep(1)
print(text)
async def main():
print("tim")
task = asyncio.create_task(foo("text"))
await asyncio.sleep(1)
print("finished")
asyncio.run(main())
The output is:
tim
text
finished
text
However, when I change the sleep time in the main() function to 0.5:
import asyncio
async def foo(text):
print(text)
await asyncio.sleep(1)
print(text)
async def main():
print("tim")
task = asyncio.create_task(foo("text"))
await asyncio.sleep(0.5)
print("finished")
asyncio.run(main())
The output is:
tim
text
finished
Then, when I change the sleep time in the main() function to 0.99:
import asyncio
async def foo(text):
print(text)
await asyncio.sleep(1)
print(text)
async def main():
print("tim")
task = asyncio.create_task(foo("text"))
await asyncio.sleep(0.99)
print("finished")
asyncio.run(main())
The output is:
tim
text
finished
text
May I ask why the final 'text' is printed in the first and third cases but not printed in the second case? Thank you.
One more question:
In the first case, if asyncio.run() ends after print("finished") in the main() function, why print(text) in the foo() task is still executed. Is this because of the granularity of about 15 milliseconds as said in @Paul Cornelius's answer?
Furthermore, I add an additional time.sleep() in the main() function, so the await in the foo() task ends obviously earlier than the finish of the main() task. The program does not execute foo() task after print("finished") in this case:
async def foo(text):
print(text)
await asyncio.sleep(1)
print(text)
async def main():
print("tim")
task = asyncio.create_task(foo("text"))
await asyncio.sleep(0.5)
time.sleep(1)
print("finished")
asyncio.run(main())
The output is:
tim
text
finished
However, the program does execute foo() task after print("finished") in this case:
async def foo(text):
print(text)
await asyncio.sleep(1)
print(text)
async def main():
print("tim")
task = asyncio.create_task(foo("text"))
await asyncio.sleep(1)
time.sleep(1)
print("finished")
asyncio.run(main())
The output is:
tim
text
finished
text