- Notifications
You must be signed in to change notification settings - Fork 13
Expand file tree
/
Copy pathlesson02_cancel_task.py
More file actions
Latest commit
29 lines (26 loc) · 735 Bytes
/
Copy pathlesson02_cancel_task.py
File metadata and controls
29 lines (26 loc) · 735 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
# SuperFastPython.com
# example of canceling an asyncio task
importasyncio
# define a coroutine for a task
asyncdeftask_coroutine():
# report a message
print('executing the task')
# suspend for a moment
awaitasyncio.sleep(1)
# custom coroutine
asyncdefmain():
# report a message
print('main coroutine')
# create and schedule the task
task=asyncio.create_task(task_coroutine())
# wait a moment
awaitasyncio.sleep(0.5)
# cancel the task
was_cancelled=task.cancel()
print(f'>was canceled: {was_cancelled}')
# wait a moment
awaitasyncio.sleep(0.1)
# report the status
print(f'>canceled: {task.cancelled()}')
# start the asyncio program
asyncio.run(main())