Files
chongming-utils-task/examples/01_quickstart.py
T

50 lines
1.4 KiB
Python
Raw Normal View History

"""示例 1:跑一个任务,并观察它在生命周期中经过的状态。
运行::
uv run python examples/01_quickstart.py
"""
from __future__ import annotations
import time
from chongming_task.run import TaskRun
from chongming_task.runtime.cancellation import CancellationToken
def extract(ctx: CancellationToken, source: str) -> list[int]:
"""模拟一次数据抽取。
要点:长耗时循环里必须周期性地调用 ``ctx.checkpoint()``。它同时做三件事:
响应停止请求、响应暂停请求、刷新心跳。
"""
rows: list[int] = []
for index in range(5):
ctx.checkpoint()
time.sleep(0.05)
rows.append(index)
print(f" 抽取完成:{source} -> {len(rows)} 行")
return rows
def main() -> None:
run = TaskRun(extract, ("s3://demo/rows",), task_id="demo-1", name="抽取")
run.start()
outcome = run.wait(timeout=30)
print("\n状态迁移历史(只追加、可审计):")
for record in run.transitions:
print(
f" {record.from_status.value:>10} -> {record.to_status.value:<10} by {record.trigger}"
)
print(f"\n最终状态:{outcome.status.value}")
print(f"返回值 :{outcome.value}")
elapsed = (outcome.snapshot.ended_at - outcome.snapshot.started_at).total_seconds()
print(f"耗时 :{elapsed:.2f}s")
if __name__ == "__main__":
main()