Skip to main content

moduvex_runtime/time/
mod.rs

1//! Async timer primitives: [`sleep`], [`sleep_until`], [`interval`].
2//!
3//! All timers are driven by a per-thread hierarchical timer wheel integrated
4//! into the executor run loop. The wheel is ticked each iteration of the loop;
5//! expired timers fire their wakers, re-scheduling the waiting tasks.
6//!
7//! # Thread-local timer wheel
8//! The `TIMER_WHEEL` thread-local holds the wheel for the current executor
9//! thread. `with_timer_wheel` provides safe, borrow-scoped mutable access.
10
11pub mod interval;
12pub mod sleep;
13pub mod wheel;
14
15pub use interval::{interval, Interval};
16pub use sleep::{sleep, sleep_until, Sleep};
17pub(crate) use wheel::{TimerId, TimerWheel};
18
19use std::cell::RefCell;
20use std::time::Instant;
21
22// ── Thread-local timer wheel ──────────────────────────────────────────────────
23
24thread_local! {
25    /// Per-thread timer wheel. Lazily initialised on first access.
26    /// Origin is captured once at init time and stays fixed.
27    static TIMER_WHEEL: RefCell<TimerWheel> =
28        RefCell::new(TimerWheel::new(Instant::now()));
29}
30
31/// Mutably borrow the thread-local timer wheel for the duration of `f`.
32///
33/// # Panics
34/// Panics on re-entrant borrow (same contract as `RefCell::borrow_mut`).
35pub(crate) fn with_timer_wheel<F, R>(f: F) -> R
36where
37    F: FnOnce(&mut TimerWheel) -> R,
38{
39    TIMER_WHEEL.with(|cell| f(&mut cell.borrow_mut()))
40}
41
42/// Tick the thread-local timer wheel to `now`, returning expired wakers.
43///
44/// Called by the executor run loop every iteration.
45pub(crate) fn tick_timer_wheel(now: Instant) -> Vec<std::task::Waker> {
46    with_timer_wheel(|w| w.tick(now))
47}
48
49/// Return the nearest pending deadline from the thread-local timer wheel.
50///
51/// Used by the executor to compute the reactor poll timeout.
52pub(crate) fn next_timer_deadline() -> Option<Instant> {
53    with_timer_wheel(|w| w.next_deadline())
54}