I didn't have a good sample code for ʻasyncio`, but On-demand data in Python, Part 3 Coroutines and asyncio -on-demand-data-python-3 / index.html) explained with a more specific story that the waiter in the restaurant handles multiple orders, so it is the easiest to understand and helpful. .. Frequently seen Understanding async / await in python3 and [Asynchronous processing in Python: asyncio reverse lookup](https://qiita.com/icoxfog417/ Better than items / 07cbf5110ca82629aca0).
import asyncio
import time
async def start_time(src):
await asyncio.sleep(src)
print("START!!!")
async def main_process(span):
idx = 1
while True:
await asyncio.sleep(span)
num_active_tasks = len([ task for task in asyncio.Task.all_tasks(loop) if not task.done()])
if num_active_tasks == 1:
break
print("[run:{}]{}Seconds have passed".format(num_active_tasks, idx * span))
idx += 1
async def end_time(src):
await asyncio.sleep(src)
print("END!!!")
if __name__ == "__main__":
loop = asyncio.get_event_loop()
try:
loop.run_until_complete(
asyncio.gather(
start_time(10),
main_process(1),
end_time(20)
)
)
finally:
loop.close()
The point of interest is
len([ task for task in asyncio.Task.all_tasks(loop) if not task.done()])
You can get the currently resident task by doing ʻasyncio.Task.all_tasks (loop) if not task.done () `.
The output result is as follows. If only the main process is running, it is out of the loop.
[run:3]1 second has passed
[run:3]2 seconds have passed
[run:3]3 seconds have passed
[run:3]4 seconds have passed
[run:3]5 seconds have passed
[run:3]6 seconds have passed
[run:3]7 seconds have passed
[run:3]8 seconds have passed
[run:3]9 seconds have passed
START!!!
[run:2]10 seconds have passed
[run:2]11 seconds have passed
[run:2]12 seconds have passed
[run:2]13 seconds have passed
[run:2]14 seconds have passed
[run:2]15 seconds have passed
[run:2]16 seconds have passed
[run:2]17 seconds have passed
[run:2]18 seconds have passed
[run:2]19 seconds have passed
END!!!
ʻAsyncio.Task.all_tasks () is deprecated in Python 3.7 and later and will be removed in 3.9. Especially in the part of ʻasyncio
, the writing style seems to change considerably every time the version goes up.
(See Python3.8 doc Task Object)
-Python3.6 doc 18.5.3. Tasks and coroutines -On-demand data in Python, Part 3 Coroutines and asyncio -Understanding async / await for python3 -Asynchronous processing in Python: asyncio reverse lookup reference
Recommended Posts