- Notifications
You must be signed in to change notification settings - Fork 13
Expand file tree
/
Copy pathlesson03_wait_for.py
More file actions
Latest commit
28 lines (25 loc) · 726 Bytes
/
Copy pathlesson03_wait_for.py
File metadata and controls
28 lines (25 loc) · 726 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
# SuperFastPython.com
# example of waiting for a coroutine with a timeout
fromrandomimportrandom
importasyncio
# coroutine to execute in a new task
asyncdeftask_coro():
# generate a random value between 0 and 1
value=1+random()
# report message
print(f'>task got {value}')
# suspend for a moment
awaitasyncio.sleep(value)
# report all done
print('>task done')
# main coroutine
asyncdefmain():
# create a task
task=task_coro()
# execute and wait for the task without a timeout
try:
awaitasyncio.wait_for(task, timeout=0.2)
exceptasyncio.TimeoutError:
print('Gave up waiting, task canceled')
# start the asyncio program
asyncio.run(main())