Issue
I have a program like this
task_2_running = False
async def task2():
task_2_running = True
await do_something()
task_2_running = False
async def main():
while True:
x = await task1()
do_something(x)
if some_condition(x) and not task_2_running:
#Do task2() but don't wait until it finished
loop = asyncio.get_event_loop()
loop.run_until_complete(main())
How do I call task2()
so the loop will continue without waiting for task2()
to finish, and task2()
will still finish sometime in the future?
Solution
You could use asyncio.create_task, a sample as next:
test.py:
import time
task_2_running = False
async def task1():
time.sleep(3)
async def task2():
print("task2 run")
task_2_running = True
await asyncio.sleep(5)
task_2_running = False
print("task2 finish")
async def main():
while True:
print("main run")
x = await task1()
if not task_2_running:
print("create task2")
#Do task2() but don't wait until it finished
asyncio.create_task(task2())
await asyncio.sleep(1)
loop = asyncio.get_event_loop()
loop.run_until_complete(main())
Execution:
$ python3 test.py
main run
create task2
task2 run
main run
create task2
task2 run
task2 finish
main run
create task2
task2 run
^C
From the execution, you could see after task2 run
, the main run
did not wait for task2 finish
, just continue to run next loop to print another main run
.
BTW, asyncio.create_task
just for python3.7 and higher, for < python3.7
, you may need to use asyncio.ensure_future()
, see this:
async def coro():
...
# In Python 3.7+
task = asyncio.create_task(coro())
...
# This works in all Python versions but is less readable
task = asyncio.ensure_future(coro())
...
Answered By - atline
0 comments:
Post a Comment
Note: Only a member of this blog may post a comment.