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())
...