-
Notifications
You must be signed in to change notification settings - Fork 1
Expand file tree
/
Copy pathasyncio_task.py
More file actions
81 lines (64 loc) · 2.4 KB
/
Copy pathasyncio_task.py
File metadata and controls
81 lines (64 loc) · 2.4 KB
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
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
#!/usr/bin/env python3
# -*- coding: utf-8 -*-
import asyncio
import time
async def say_after(delay, what):
await asyncio.sleep(delay)
print(what)
async def run_task_sync():
print("\nrun task sync")
print(f"started at {time.strftime('%X')}")
await say_after(1, 'sleep 1')
await say_after(2, 'sleep 2')
print(f"finished at {time.strftime('%X')}")
async def run_task_concurrent_format1():
print("\ncreate task, and run concurrent")
task1 = asyncio.create_task(say_after(1, 'sleep 1'))
task2 = asyncio.create_task(say_after(2, 'sleep 2'))
print(f"started at {time.strftime('%X')}")
await task1
await task2
print(f"finished at {time.strftime('%X')}")
async def run_task_concurrent_format2():
print("\ngather task, and run concurrent")
print(f"started at {time.strftime('%X')}")
await asyncio.gather(
say_after(1, "sleep 1"),
say_after(2, "sleep 2"),
)
print(f"finished at {time.strftime('%X')}")
async def wait_task_timeout():
print("\nwait task finish, by timeout")
# Wait for at most 1 second
try:
await asyncio.wait_for(say_after(3, "should not appear"), timeout=1.0)
except asyncio.TimeoutError:
print('timeout!')
async def wait_task_only_one_complete():
print("\nwait one task complete")
try:
task_sleep_2 = asyncio.create_task(say_after(2, "sleep 2"))
task_sleep_1 = asyncio.create_task(say_after(1, "sleep 1"))
task_sleep_3 = asyncio.create_task(say_after(3, "sleep 3"))
task_sleep_1.add_done_callback(lambda res: print("done task_sleep_1"))
done, pending = await asyncio.wait(
{task_sleep_2, task_sleep_1, task_sleep_3},
timeout=5,
return_when=asyncio.FIRST_COMPLETED) #FIRST_EXCEPTION/ALL_COMPLETED
if task_sleep_1 in done:
print("task_sleep_1 in done")
for task in pending:
task.cancel()
try:
for task in pending:
await task
except asyncio.CancelledError:
print("have canceled, should NOT await")
except asyncio.TimeoutError:
print('timeout!')
if __name__ == "__main__":
asyncio.run(wait_task_only_one_complete())
asyncio.run(wait_task_timeout())
asyncio.run(run_task_concurrent_format2())
asyncio.run(run_task_concurrent_format1())
asyncio.run(run_task_sync())