import asyncio
async def while_loop():
n = 0
while True:
print(f"{n}")
await asyncio.sleep(2)
n = n + 1
async def some_func():
await asyncio.sleep(5)
print("Some Func")
# https://stackoverflow.com/questions/50592540/asyncio-create-task-to-run-forever
# I expected the numbers to keep printing even after some_func is completed.
loop = asyncio.get_event_loop()
def x_test1():
"""loop.run_until_complete(some_func()) - run the event loop until the some_func coroutine finishes.
Executes other coroutines in parallel during that time as well, but also stops executing them as soon
as the event loop finishes.
"""
future = loop.create_task(while_loop())
loop.run_until_complete(some_func())
def x_test2():
future = loop.create_task(while_loop())
loop.run_until_complete(some_func())
loop.run_until_complete(some_func())
def x_test3():
"""loop.run_forever() - run the event loop until some coroutine or callback invokes loop.stop().
If none of them do that, then the event loop will not halt, even if all the coroutines come to an end.
In your case you'd call loop.create_task(while_loop()) followed by loop.create_task(some_func()) and
then loop.run_forever().
"""
loop.create_task(while_loop())
loop.create_task(some_func())
loop.run_forever()
def x_test4():
"""
loop.run_until_complete(asyncio.gather(while_loop(), some_func())) run the event loop until both the specified
coroutines finish. This (wait for all the tasks) is apparently what you expected loop.run_until_complete()
to do automatically even if you name only one, except it doesn't work like that, it stops as soon as the
specified coroutine finishes. asyncio.gather can be used to wait for multiple coroutines at once.
For a more fine-tuned control of waiting, also see asyncio.wait.
"""
loop.run_until_complete(asyncio.gather(while_loop(), some_func()))
if __name__ == '__main__':
x_test2()
网友评论