-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathcancellation.py
More file actions
57 lines (42 loc) · 1.31 KB
/
Copy pathcancellation.py
File metadata and controls
57 lines (42 loc) · 1.31 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
"""Task cancellation with offwork.
Demonstrates cancelling a pending or in-progress task.
Usage:
# Terminal 1 -- start a worker
offwork worker --backend local://localhost:9748 --tmp
# Terminal 2 -- run this script
offwork run examples/cancellation.py
"""
import asyncio
import offwork
from offwork import TaskCancelled
offwork.connect("local://localhost:9748")
@offwork.task
async def slow_computation(n: int) -> int:
"""A deliberately slow function."""
total = 0
try:
for _ in range(n):
await asyncio.sleep(1.0)
total += 1
return total
finally:
if total < n:
print(f"Task interrupted after {total}/{n} iterations")
async def main() -> None:
# Start a slow task
future = await slow_computation.submit(10)
print(f"Task submitted: {future.task_id}")
# Wait briefly, then cancel it
await asyncio.sleep(3.0)
print("Cancelling task...")
await future.cancel()
# Awaiting a cancelled task raises TaskCancelled
try:
result = await future
print(f"Unexpected result: {result}")
except TaskCancelled:
print("Task was cancelled successfully!")
# Verify the status
print(f"Task cancelled: {future.cancelled()}") # True
if __name__ == "__main__":
asyncio.run(main())