Skip to main content

timeout_basic/
basic.rs

1//! Run with: `cargo run -p reliakit-timeout --example timeout_basic`
2//!
3//! A clock-agnostic deadline driving a small retry loop. Time is a `u64` in
4//! whatever monotonic unit you like; this example uses milliseconds and a fake
5//! clock so the output is deterministic.
6
7use reliakit_timeout::{Deadline, Timeout};
8
9fn main() {
10    // A 1-second budget for the whole operation.
11    let policy = Timeout::new(1_000);
12
13    // Pretend the operation starts at t = 0.
14    let deadline: Deadline = policy.start(0);
15    println!(
16        "budget: {} ms, expires at t = {}",
17        policy.budget(),
18        deadline.expiry()
19    );
20
21    // A fake monotonic clock and a fixed retry delay.
22    let mut now = 0;
23    let attempt_cost = 250; // each attempt + wait advances the clock by this much
24
25    for attempt in 1.. {
26        match deadline.check(now) {
27            None => {
28                println!(
29                    "t = {now}: deadline expired, giving up after {} attempts",
30                    attempt - 1
31                );
32                break;
33            }
34            Some(remaining) => {
35                // Never wait longer than the time left in the budget.
36                let wait = deadline.clamp(now, attempt_cost);
37                println!("t = {now}: attempt {attempt} ({remaining} ms left, waiting {wait} ms)");
38                now += attempt_cost;
39            }
40        }
41    }
42}