跳到主要内容

Timer

查看 Markdown

Timer 是一个等到某个时间点的 durable 等待,由 Dex Server 保存。Step 在 WaitFor 中返回它,Timer 触发后运行 Execute。Step 等待期间,没有 Worker 为它占用内存、线程或连接。

什么时候用 Timer​

Timer 适合延迟、提醒或截止时间。把它和另一个 condition 组合,就能实现超时。例如,一个 Step 同时等待 Channel 消息和 Timer,哪个先到就继续。在 Execute 中,Step 检查它的 Timer 是否已触发。

保证​

server 把 Timer 和 Flow 一起保存。Worker 重启和 server failover 都不会丢失它。

等待 Timer​

这个 Step 等待输入中给出的秒数:

timer_flow.pyPython
class TimerExampleStep(Step[int]):
def wait_for(self, _context: Context, input: int) -> Wait:
return Wait.until(Timer.by_duration(timedelta(seconds=input)))

def execute(self, context: Context, _input: int) -> StepDecision:
print(context.has_timer_fired())
return graceful_complete("timer-fired")

例子: examples/python/dex_examples/primitives/timer/timer_flow.py

跳过 Timer​

Client 可以用 SkipTimer 跳过一个 Timer。它按 Flow ID、Step execution ID,以及 Timer 的 condition ID 或它在 WaitFor 中的 condition 序号选择 Timer。被跳过的 Timer 等同于已经触发。在测试中可以用它;在生产中,也可以用它让等待中的 Step 提前运行。见 Skip a Timer。

在 order-processing 示例的这个测试里,Ship Step 等待一个 Timer,测试跳过了它:

test_order_processing.pyPython
await client.skip_timer(
flow_id,
SHIP_STEP,
TimerId.by_condition_index(0),
)

例子: examples/python/tests/integ/test_order_processing.py

Step 如何在 WaitFor 中组合 condition,见 Step。

参考​

每个 SDK 参考的 Timer 页列出该语言的 API 名称。

  • Waits 和 Condition results 说明 Timer 如何与其他 condition 组合,以及 Step 如何读取哪个 condition 已经触发。
  • Skip a Timer 说明这个 Client 调用。