---
title: "Polling with WaitFor Timer"
description: "Polling with a WaitFor Timer checks an external system once per round, and each round is a new Step execution. Use it when a Flow waits for a cloud build, a provisioning job, or a third-party status, and you want to see every round in the Flow's history."
canonical_url: "https://docs.superdurable.io/design-patterns/durable-timer/polling-with-wait-for-timer/"
source: "docs/content/design-patterns/durable-timer/polling-with-wait-for-timer.mdx"
locale: "en"
language: "python"
---

> Index of every page for AI agents: https://docs.superdurable.io/llms.txt

# Polling with WaitFor Timer

Code on this page is in Python. Other languages: [Go](https://docs.superdurable.io/design-patterns/durable-timer/polling-with-wait-for-timer.go.md) · [Java](https://docs.superdurable.io/design-patterns/durable-timer/polling-with-wait-for-timer.java.md) · [TypeScript](https://docs.superdurable.io/design-patterns/durable-timer/polling-with-wait-for-timer.typescript.md) · [Rust](https://docs.superdurable.io/design-patterns/durable-timer/polling-with-wait-for-timer.rust.md)

Polling with a WaitFor Timer checks an external system once per round, and each round is a new Step execution. Use it when a Flow waits for a cloud build, a provisioning job, or a third-party status, and you want to see every round in the Flow's history.

The polling Step waits for a Timer in `WaitFor`. Its `Execute` calls the external system once. While the work is not finished, the Step moves to itself for the next round.

**Flow graph: PollingWithTimerFlow**

**Steps**

1. `StartJob` (start Step): Start the external job. Next: `CheckJobStatus`.
2. `CheckJobStatus`: Wait for the interval Timer, then check the job once. Next: `CheckJobStatus` again, the Flow completes, the Flow fails, or `RecordJobWaitFailure` if it keeps failing.
3. `RecordJobWaitFailure`: Fail the Flow with the reason the status check failed. Next: the Flow fails.

Example: [examples/python/dex_examples/patterns/polling-with-timer/polling_with_timer_flow.py](https://github.com/superdurable/dex/tree/main/examples/python/dex_examples/patterns/polling-with-timer/polling_with_timer_flow.py)

<a id="shape"></a>

## Shape

Each round of the polling Step runs these steps:

1. `WaitFor` returns a Timer for the polling interval.
2. When the Timer fires, `Execute` calls the external API once, with its own short timeout.
3. On a transient error, `Execute` returns the error. The retry policy runs the round again.
4. On a terminal status, `Execute` returns the next decision: success or a business failure.
5. While the work is not finished, `Execute` returns `GoTo` to the same Step with the next round's input.

"Not ready yet" is a normal decision. Prefer it to returning an error and letting retries loop. An error mixes "not ready" with real failures and spends the retry budget.

<a id="rules"></a>

## Rules

- <a id="not-ready"></a>Return `GoTo` to the same Step when the work is not
  ready. Each `GoTo` starts a new Step execution, which waits for a new Timer.
- <a id="bound-the-loop"></a>Bound the loop. Carry a round number in the Step
  input and stop at a maximum. The round limit bounds the number of checks.
  It does not bound the elapsed time: each round also spends time on the
  external call, retries, and queueing. For a hard deadline, use the
  [Flow timeout](https://docs.superdurable.io/reference/python/start-flow-options.md#timeout-and-timeout-policy)
  or a [deadline watchdog](https://docs.superdurable.io/design-patterns/durable-timer/polling-with-long-running-step-heartbeat.md#rules).
- <a id="step-input"></a>Keep the Step input small and fixed in size, such as
  the job ID and the round number. Keep accumulated state, such as collected
  results, in Attributes, never in a growing Step input.
- <a id="external-calls"></a>Check the job status in `Execute`.
  Never poll the external system from `WaitFor`.
  In this pattern, `WaitFor` only declares the Timer.
- <a id="retries"></a>Give `ExecuteRetry` a few attempts with backoff for
  transient errors. Route exhausted retries with the `ExecuteFailure` option
  to a short Step that records the failure; see
  [Execute Failure Recovery](https://docs.superdurable.io/design-patterns/failure-handling/execute-failure-recovery.md).
- <a id="interval"></a>Timers count whole seconds. For an interval below a
  few seconds, use
  [Polling with Long-Running Step Heartbeat](https://docs.superdurable.io/design-patterns/durable-timer/polling-with-long-running-step-heartbeat.md).
- <a id="tests"></a>Give the Timer a condition ID. In tests, skip it with
  `SkipTimer` instead of shortening the interval; see
  [Skip a Timer](https://docs.superdurable.io/concepts/primitives/timer.md#skip-a-timer).

## Example

`PollingWithTimerFlow` waits for the same simulated job as the [heartbeat example](https://docs.superdurable.io/design-patterns/durable-timer/polling-with-long-running-step-heartbeat.md#example). `StartJob` starts the job with the Flow ID as an idempotent job ID. `CheckJobStatus` waits for a 10-second Timer, then reads the job status once. While the job runs, it moves to itself with the next round number. It stops after 60 rounds. When its retries run out, it moves to `RecordJobWaitFailure`, which fails the Flow with the recovery error.

The simulated job succeeds six seconds after it starts, so the first round finds it finished. Call the complete-job endpoint to finish it early.

**Python**

```python
# MAX_POLL_ROUNDS bounds the number of checks, not elapsed time; calls, retries, and queueing add time.
POLL_INTERVAL = timedelta(seconds=10)
POLL_INTERVAL_TIMER_ID = "poll-interval"
MAX_POLL_ROUNDS = 60
JOB_CALL_TIMEOUT = timedelta(seconds=10)


@dataclass(frozen=True)
class JobPollRound:
    job_id: str
    round_number: int


class CheckJobStatus(Step[JobPollRound]):
    def __init__(self, jobs: FakeJobService) -> None:
        self.jobs = jobs

    def get_step_options(self) -> StepOptions:
        return StepOptions(
            execute_retry=RetryPolicy(
                initial_interval=timedelta(seconds=1),
                backoff_coefficient=2.0,
                maximum_attempts=3,
            ),
        ).on_execute_failure_proceed_to(RecordJobWaitFailure)

    def wait_for(self, context: Context, poll_round: JobPollRound) -> Wait:
        return Wait.until(
            Timer.by_duration(POLL_INTERVAL, condition_id=POLL_INTERVAL_TIMER_ID)
        )

    async def execute(
        self, context: AsyncContext, poll_round: JobPollRound
    ) -> StepDecision:
        status = await asyncio.wait_for(
            self.jobs.get_job_status(poll_round.job_id),
            JOB_CALL_TIMEOUT.total_seconds(),
        )
        if status.state is JobState.SUCCEEDED:
            return graceful_complete(status.result)
        if status.state is JobState.FAILED:
            return force_fail(f"job {poll_round.job_id} failed")
        if poll_round.round_number >= MAX_POLL_ROUNDS:
            return force_fail(
                f"job {poll_round.job_id} did not finish in {MAX_POLL_ROUNDS} rounds"
            )
        next_round = JobPollRound(poll_round.job_id, poll_round.round_number + 1)
        return go_to(CheckJobStatus, next_round)
```

Example: [examples/python/dex_examples/patterns/polling-with-timer/polling_with_timer_flow.py](https://github.com/superdurable/dex/tree/main/examples/python/dex_examples/patterns/polling-with-timer/polling_with_timer_flow.py)

<a id="compare"></a>

## Compare the polling patterns

Polling with WaitFor Timer records every round in the Flow's history. You see each round clearly, and you can Time Travel back to a round. It is somewhat heavier.

[Polling with Long-Running Step Heartbeat](https://docs.superdurable.io/design-patterns/durable-timer/polling-with-long-running-step-heartbeat.md) is lighter. One Step execution holds the whole wait.

| Behavior            | WaitFor Timer                                                                                                           | Long-running Step heartbeat                      |
| ------------------- | ----------------------------------------------------------------------------------------------------------------------- | ------------------------------------------------ |
| Each round          | A new Step execution in the Flow's history                                                                              | A heartbeat or Stream message inside one attempt |
| Between rounds      | No Worker task slot is held                                                                                             | The attempt holds a Worker task slot             |
| Dex Server failover | A Timer wait continues and uses no retry; a `WaitFor` or `Execute` attempt a Worker had received fails and uses a retry | The running attempt fails and uses a retry       |
| Interval            | Whole seconds                                                                                                           | Any interval                                     |

[Lease](https://docs.superdurable.io/reference/server/high-availability.md#lease) gives the exact failover rules, including the ASYNC exception.

Choose this pattern for long intervals, to see each round, or to Time Travel to a round. Choose the heartbeat pattern for short intervals or the lightest loop. Time Travel reaches a round only inside the run's recent history window; see [Recover a Flow with Time Travel](https://docs.superdurable.io/components/operate-and-debug.md#time-travel).

## Next

- [Polling with Long-Running Step Heartbeat](https://docs.superdurable.io/design-patterns/durable-timer/polling-with-long-running-step-heartbeat.md)
- [Timer](https://docs.superdurable.io/concepts/primitives/timer.md)
- [Reminder](https://docs.superdurable.io/design-patterns/durable-timer/reminder.md)
- [Execute Failure Recovery](https://docs.superdurable.io/design-patterns/failure-handling/execute-failure-recovery.md)
