Skip to main content

base_scheduler/
timers.rs

1// Released under the MIT License.
2// Copyright, 2026, by Samuel Williams.
3
4use crate::{Cancellation, Clock, OperationResult};
5use std::{future::Future, time::Instant};
6
7/// Experimental reusable timer capability for the timer benchmark. This is not a settled public contract.
8///
9/// Construct resources through `timer` to establish their scheduler compatibility before waiting. Waiting always receives its scheduler and cancellation explicitly; incompatible scheduler/resource pairings are rejected with `io::ErrorKind::InvalidInput`. Only one waiter can borrow the resource. Dropping a wait retains its registration, which may cause a later wake of the previous task. Dropping the resource retires it; forgetting it may leak registration capacity but cannot retain borrowed application memory. Cancellation observed after admission disarms its registration; pre-cancellation leaves existing state unchanged. Deadline replacement happens on first poll, including an earlier replacement.
10///
11/// ```
12/// use base_scheduler::{Cancellation, OperationResult, Timers};
13/// use std::time::Duration;
14///
15/// async fn delay<S: Timers>(scheduler: &S, cancellation: &Cancellation) -> OperationResult<()> {
16///     let mut timer = scheduler.timer();
17///     let deadline = scheduler.now() + Duration::from_secs(1);
18///     scheduler.timer_wait_until(&mut timer, deadline, cancellation).await
19/// }
20/// ```
21pub trait Timers: Clock {
22    /// Reusable timer state created by [`timer`](Self::timer) and borrowed by each [`timer_wait_until`](Self::timer_wait_until).
23    type Timer: Send;
24
25    /// Construct reusable state compatible with this scheduler, without registering a deadline or selecting a worker. Construction is infallible even after closure; waits retain the backend's clock admission rules.
26    fn timer(&self) -> Self::Timer;
27
28    /// Wait until an absolute deadline using retained timer state. Constructing an unpolled future leaves the resource unchanged.
29    fn timer_wait_until(
30        &self,
31        timer: &mut Self::Timer,
32        deadline: Instant,
33        cancellation: &Cancellation,
34    ) -> impl Future<Output = OperationResult<()>> + Send;
35}