75 lines
2.1 KiB
Python
75 lines
2.1 KiB
Python
"""示例 2:运行期干预 —— 暂停、恢复、停止。
|
||||
|
|
|
|||
|
|
演示协作式暂停(D6 定案的语义)与"停不掉时会如实上报"。
|
|||
|
|
|
|||
|
|
运行::
|
|||
|
|
|
|||
|
|
uv run python examples/02_control.py
|
|||
|
|
"""
|
|||
|
|
|
|||
|
|
from __future__ import annotations
|
|||
|
|
|
|||
|
|
import time
|
|||
|
|
|
|||
|
|
from chongming_task.run import TaskRun
|
|||
|
|
|
|||
|
|
|
|||
|
|
def long_running(ctx) -> str:
|
|||
|
|
"""持续做小步工作,每一步都经过协作点。"""
|
|||
|
|
for _ in range(10_000):
|
|||
|
|
ctx.checkpoint()
|
|||
|
|
time.sleep(0.01)
|
|||
|
|
return "跑完了"
|
|||
|
|
|
|||
|
|
|
|||
|
|
def uncooperative(ctx) -> str:
|
|||
|
|
"""刻意**不**调用 checkpoint:这样的任务既停不掉也暂停不了。
|
|||
|
|
|
|||
|
|
它约 4 秒后自行结束,以免在示例里留下后台线程。
|
|||
|
|
"""
|
|||
|
|
for _ in range(400):
|
|||
|
|
time.sleep(0.01)
|
|||
|
|
return "无视了停止请求"
|
|||
|
|
|
|||
|
|
|
|||
|
|
def demo_pause_resume() -> None:
|
|||
|
|
print("== 暂停 / 恢复 ==")
|
|||
|
|
run = TaskRun(long_running, task_id="demo-pause")
|
|||
|
|
run.start()
|
|||
|
|
time.sleep(0.2)
|
|||
|
|
|
|||
|
|
print(f" 暂停请求已受理:{run.pause(timeout=5)};当前状态 {run.status.value}")
|
|||
|
|
time.sleep(0.2)
|
|||
|
|
print(f" 暂停期间状态保持:{run.status.value}")
|
|||
|
|
|
|||
|
|
run.resume()
|
|||
|
|
print(f" 恢复后状态 :{run.status.value}")
|
|||
|
|
|
|||
|
|
run.stop(reason="演示主动停止")
|
|||
|
|
outcome = run.wait(timeout=10)
|
|||
|
|
print(f" 停止后终态 :{outcome.status.value}")
|
|||
|
|
print(f" 失败归类 :{outcome.failure.kind.value if outcome.failure else '-'}")
|
|||
|
|
print(f" 可重试 :{outcome.failure.retryable if outcome.failure else '-'}")
|
|||
|
|
|
|||
|
|
|
|||
|
|
def demo_unstoppable() -> None:
|
|||
|
|
print("\n== 停不掉的任务:如实上报 ==")
|
|||
|
|
run = TaskRun(uncooperative, task_id="demo-stubborn", graceful_stop=0.3)
|
|||
|
|
run.start()
|
|||
|
|
time.sleep(0.2)
|
|||
|
|
run.stop(reason="试一下")
|
|||
|
|
|
|||
|
|
outcome = run.wait(timeout=10)
|
|||
|
|
print(f" 终态 :{outcome.status.value}")
|
|||
|
|
print(f" 失败归类 :{outcome.failure.kind.value if outcome.failure else '-'}")
|
|||
|
|
print(" 含义 :线程无法强杀,任务可能仍在后台产生副作用,因此不敢说'已停止'")
|
|||
|
|
|
|||
|
|
|
|||
|
|
def main() -> None:
|
|||
|
|
demo_pause_resume()
|
|||
|
|
demo_unstoppable()
|
|||
|
|
|
|||
|
|
|
|||
|
|
if __name__ == "__main__":
|
|||
|
|
main()
|