-
Notifications
You must be signed in to change notification settings - Fork 1
Expand file tree
/
Copy pathasyncio_wait_timeout.py
More file actions
36 lines (29 loc) · 956 Bytes
/
asyncio_wait_timeout.py
File metadata and controls
36 lines (29 loc) · 956 Bytes
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
import asyncio
async def phase(i):
print("in phase {}".format(i))
try:
await asyncio.sleep(0.1 * i)
except asyncio.CancelledError:
print("phase {} canceled".format(i))
raise
else:
print("done with phase {}".format(i))
return "phase {} result".format(i)
async def main(num_phases):
print("starting main")
phases = [phase(i) for i in range(num_phases)]
print("waiting 0.1 for phases to complete")
completed, pending = await asyncio.wait(phases, timeout=0.1)
print("{} completed and {} pending".format(len(completed), len(pending)))
# Cancel remaining tasks so they do not generate errors
# as we exit without finishing them.
if pending:
print("canceling tasks")
for t in pending:
t.cancel()
print("exiting main")
event_loop = asyncio.get_event_loop()
try:
event_loop.run_until_complete(main(3))
finally:
event_loop.close()