Issue
How can I properly close asyncio infinite loop task upon reaching certain condition? Let's say I want to cancel infinite loop if the number in function reaches 20:
import asyncio
async def main(numb):
if numb == 20:
print('Reached')
get_loop = asyncio.get_running_loop()
get_loop.stop()
print(numb)
async def create_tasks():
numb = 0
while True:
x = asyncio.create_task(main(numb))
numb += 1
await x
asyncio.run(create_tasks())
Is there more proper way to do it? If I do not cancel the task asyncio way and just use "return" instead, the event loop gets hung and never prints that the script finished to the stdout.
Solution
With the code as it is there, just raise an exception on main
, it will be re-raised at the await
point.
import asyncio
class StopTasks(Exception):
pass
async def main(numb):
if numb == 20:
raise StopTasks()
print(numb)
async def create_tasks():
numb = 0
while True:
x = asyncio.create_task(main(numb))
numb += 1
try:
await x
except StopTasks:
break
asyncio.run(create_tasks())
If you are running tasks in parallel, though there are other ways to go - probably you are better using asyncio.wait and cancel the pending tasks - in that case you have to use a global variable to communicate that you are done - (it could also be an exception)
Answered By - jsbueno
0 comments:
Post a Comment
Note: Only a member of this blog may post a comment.