-
Notifications
You must be signed in to change notification settings - Fork 44
/
Copy pathmayhem_aside_4.py
57 lines (39 loc) · 1.18 KB
/
mayhem_aside_4.py
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
#!/usr/bin/env python3.7
# Copyright (c) 2018-2019 Lynn Root
"""
How to properly shield a task
Notice! This requires:
- attrs==19.1.0
To run:
$ python part-2/mayhem_aside_4.py
Follow along: https://roguelynn.com/words/asyncio-true-concurrency/
"""
import asyncio
import logging
logging.basicConfig(
level=logging.INFO,
format="%(asctime)s,%(msecs)d %(levelname)s: %(message)s",
datefmt="%H:%M:%S",
)
async def cant_stop_me():
logging.info("Can't stop me...")
for i in range(12):
logging.info("Sleeping for 5 seconds...")
await asyncio.sleep(5)
logging.info("Done!")
async def parent_task():
logging.info("Kicking of shielded task")
await asyncio.shield(cant_stop_me())
logging.info("Shielded task done")
async def imma_let_you_speak(task_to_cancel):
await asyncio.sleep(2)
logging.info(f"Interrupting {task_to_cancel}")
task_to_cancel.cancel()
async def wrapper():
parent_coro = asyncio.create_task(parent_task())
cancel_coro = imma_let_you_speak(parent_coro)
await asyncio.gather(parent_coro, cancel_coro)
async def main():
asyncio.create_task(wrapper())
await asyncio.sleep(61)
asyncio.run(main())