pub struct TimerWheel<T: 'static, S: SlabStore<Item = WheelEntry<T>> = Slab<WheelEntry<T>>> { /* private fields */ }Expand description
A multi-level, rebalancing timer wheel.
Generic over:
T— the user payload stored with each timer.S— the slab storage backend. Defaults tounbounded::Slab.
§Thread Safety
Send but !Sync. Can be moved to a thread at setup but must not
be shared. All internal raw pointers point into owned allocations
(slab chunks, level slot arrays) — moving the wheel moves the heap
data with it.
Implementations§
Source§impl<T: 'static> TimerWheel<T>
impl<T: 'static> TimerWheel<T>
Sourcepub fn unbounded(chunk_capacity: usize, now: Instant) -> Self
pub fn unbounded(chunk_capacity: usize, now: Instant) -> Self
Creates an unbounded timer wheel with default configuration.
now fixes the reference epoch — pass one monotone clock source
(e.g. Instant::now()) here and to every schedule/poll. For custom
configuration, use WheelBuilder.
Source§impl<T: 'static> TimerWheel<T, Slab<WheelEntry<T>>>
impl<T: 'static> TimerWheel<T, Slab<WheelEntry<T>>>
Sourcepub fn bounded(capacity: usize, now: Instant) -> Self
pub fn bounded(capacity: usize, now: Instant) -> Self
Creates a bounded timer wheel with default configuration.
now fixes the reference epoch — pass one monotone clock source
(e.g. Instant::now()) here and to every schedule/poll. For custom
configuration, use WheelBuilder.
Source§impl<T: 'static, S: SlabStore<Item = WheelEntry<T>>> TimerWheel<T, S>
impl<T: 'static, S: SlabStore<Item = WheelEntry<T>>> TimerWheel<T, S>
Sourcepub fn schedule(&mut self, deadline: Instant, value: T) -> TimerHandle<T>
pub fn schedule(&mut self, deadline: Instant, value: T) -> TimerHandle<T>
Sourcepub fn schedule_forget(&mut self, deadline: Instant, value: T)
pub fn schedule_forget(&mut self, deadline: Instant, value: T)
Schedules a fire-and-forget timer (no handle returned).
The timer will fire during poll and the value will be collected. Cannot be cancelled.
§Panics
Panics if the backing slab is at capacity (bounded slabs only). This is a capacity planning error — size your wheel for peak load.
Source§impl<T: 'static, S: BoundedStore<Item = WheelEntry<T>>> TimerWheel<T, S>
impl<T: 'static, S: BoundedStore<Item = WheelEntry<T>>> TimerWheel<T, S>
Sourcepub fn try_schedule(
&mut self,
deadline: Instant,
value: T,
) -> Result<TimerHandle<T>, Full<T>>
pub fn try_schedule( &mut self, deadline: Instant, value: T, ) -> Result<TimerHandle<T>, Full<T>>
Attempts to schedule a timer, returning a handle on success.
Returns Err(Full(value)) if the slab is at capacity. Use this
when you need graceful error handling. For the common case where
capacity exhaustion is fatal, use schedule.
Sourcepub fn try_schedule_forget(
&mut self,
deadline: Instant,
value: T,
) -> Result<(), Full<T>>
pub fn try_schedule_forget( &mut self, deadline: Instant, value: T, ) -> Result<(), Full<T>>
Attempts to schedule a fire-and-forget timer.
Returns Err(Full(value)) if the slab is at capacity. Use this
when you need graceful error handling. For the common case where
capacity exhaustion is fatal, use schedule_forget.
Source§impl<T: 'static, S: SlabStore<Item = WheelEntry<T>>> TimerWheel<T, S>
impl<T: 'static, S: SlabStore<Item = WheelEntry<T>>> TimerWheel<T, S>
Sourcepub fn cancel(&mut self, handle: TimerHandle<T>) -> Option<T>
pub fn cancel(&mut self, handle: TimerHandle<T>) -> Option<T>
Cancels a timer and returns its value.
- If the timer is still active: unlinks from the wheel, extracts value,
frees the slab entry. Returns
Some(T). - If the timer already fired (zombie handle): frees the slab entry.
Returns
None.
Consumes the handle (no Drop runs).
Sourcepub fn free(&mut self, handle: TimerHandle<T>)
pub fn free(&mut self, handle: TimerHandle<T>)
Releases a timer handle without cancelling.
- If the timer is still active: converts to fire-and-forget (refs 2→1). Timer stays in the wheel and will fire normally during poll.
- If the timer already fired (zombie): frees the slab entry (refs 1→0).
Consumes the handle (no Drop runs).
Sourcepub fn reschedule(
&mut self,
handle: TimerHandle<T>,
new_deadline: Instant,
) -> TimerHandle<T>
pub fn reschedule( &mut self, handle: TimerHandle<T>, new_deadline: Instant, ) -> TimerHandle<T>
Reschedules an active timer to a new deadline.
Moves the entry from its current slot to the correct slot for
new_deadline without extracting or reconstructing the value.
§Panics
Panics if the timer has already fired (zombie handle). Only active timers (refs == 2) can be rescheduled.
Consumes and returns a new handle (same entry, new position).
Sourcepub fn poll(&mut self, now: Instant, buf: &mut Vec<T>) -> usize
pub fn poll(&mut self, now: Instant, buf: &mut Vec<T>) -> usize
Collects all ready (due) timers into buf, without rebalancing, and
returns how many were collected.
This is the minimal poll: it hands back the timers whose deadline has
passed and does no maintenance, so a not-yet-due entry stays in whatever
level it was placed in. Cheap on any single call — but if you only ever
call poll, entries are never moved to finer levels and a busy wheel
degrades to an O(population) scan per poll. For steady low-latency
polling, prefer poll_and_rebalance
(collect + maintain in one pass).
Sourcepub fn poll_with_limit(
&mut self,
now: Instant,
limit: usize,
buf: &mut Vec<T>,
) -> usize
pub fn poll_with_limit( &mut self, now: Instant, limit: usize, buf: &mut Vec<T>, ) -> usize
Collects up to limit ready timers into buf, without rebalancing.
Resumable: if the limit is hit, the next call continues where this one
left off (as long as now hasn’t changed). See poll for
the rebalancing tradeoff.
Returns the number collected in this call.
Sourcepub fn poll_and_rebalance(&mut self, now: Instant, buf: &mut Vec<T>) -> usize
pub fn poll_and_rebalance(&mut self, now: Instant, buf: &mut Vec<T>) -> usize
Collects all ready timers into buf and rebalances the wheel in the
same pass — the batteries-included poll. Returns how many were collected.
Collecting is unbounded; rebalancing (moving not-yet-due entries to
finer levels so future polls stay cheap) is capped at
max_rebalances_per_poll
(default unbounded). The cap only smooths rebalance work across polls — it
never delays or drops a fire.
Sourcepub fn poll_and_rebalance_with_limit(
&mut self,
now: Instant,
limit: usize,
buf: &mut Vec<T>,
) -> usize
pub fn poll_and_rebalance_with_limit( &mut self, now: Instant, limit: usize, buf: &mut Vec<T>, ) -> usize
Collects up to limit ready timers into buf and rebalances the wheel.
The collect phase is resumable like
poll_with_limit; rebalancing is capped by
max_rebalances_per_poll.
Returns the number collected in this call.
Sourcepub fn rebalance(&mut self, now: Instant, limit: usize) -> usize
pub fn rebalance(&mut self, now: Instant, limit: usize) -> usize
Proactively rebalances the wheel: moves up to limit not-yet-due
entries down to the finest level they now belong in, and returns how many
moved. Does not collect or fire anything.
This is the maintenance half of poll_and_rebalance,
exposed on its own so you can move it off the collect hot path.
§When to reach for this
Use poll + rebalance (instead of poll_and_rebalance) when you have a
large number of outstanding timers and want to cut the poll tail. The
cost of a poll that has work is dominated by walking a fat coarse slot to
find the ready timers; by pulling entries down to exact fine-level slots
before their slot comes due, rebalance keeps that walk small, so the
collect stays cheap and flat. In practice this moves the poll-tail work
off the hot path onto rebalance, roughly quartering the collect’s p99.9
on a busy wheel — at the price of doing the maintenance yourself, when it
suits you.
§Recommended pattern: opportunistic + bounded
Rebalance only when a poll came back empty — i.e. during genuine slack —
and bound each call so a high-frequency loop spreads the work instead of
stalling on one big sweep (rebalance is resumable; the next call
continues):
let collected = wheel.poll(now, &mut buf);
if collected == 0 {
// nothing to deliver — maintain during the slack, a bounded slice
wheel.rebalance(now, REBALANCE_BUDGET);
}This self-tunes to load: busy iterations pay only the cheap collect, and the maintenance lands exactly on the idle ones. A fixed cadence (rebalance every N iterations) also works — just avoid rebalancing on every poll, which re-walks the look-ahead window and is pure overhead.
§Safety of skipping it
rebalance only visits slots whose earliest entry is already within a
finer level’s reach, and moving nothing is always safe: an un-rebalanced
entry simply fires from wherever it is sitting when its time comes. If you
never call it, the wheel still works — it just degrades to walking coarse
slots on the collect path (which is what poll_and_rebalance does for
you in one call).
Sourcepub fn next_deadline(&self) -> Option<Instant>
pub fn next_deadline(&self) -> Option<Instant>
Returns an Instant no later than when the next timer fires, or None
if the wheel is empty.
Lower bound, not exact. The per-slot minima are stale-low after a cancel/fire (they are not recomputed on removal — see the design), so the returned instant may be earlier than the true next deadline, never later. It is safe as a sleep/wake bound: you may wake early and find nothing due, but you can never miss a timer.
O(1) on cache hit; otherwise ~one compare per active slot to recompute.