Skip to main content

TimerWheel

Struct TimerWheel 

Source
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 to unbounded::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>

Source

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>>>

Source

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>

Source

pub fn schedule(&mut self, deadline: Instant, value: T) -> TimerHandle<T>

Schedules a timer and returns a handle for cancellation.

The handle must be consumed via cancel or free. Dropping it is a programming error.

§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

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>

Source

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.

Source

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>

Source

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).

Source

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).

Source

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).

Source

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).

Source

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.

Source

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.

Source

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.

Source

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.

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).

Source

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.

Source

pub fn len(&self) -> usize

Returns the number of timers currently in the wheel.

Source

pub fn is_empty(&self) -> bool

Returns true if the wheel contains no timers.

Trait Implementations§

Source§

impl<T: 'static, S: SlabStore<Item = WheelEntry<T>>> Drop for TimerWheel<T, S>

Source§

fn drop(&mut self)

Executes the destructor for this type. Read more
Source§

fn pin_drop(self: Pin<&mut Self>)

🔬This is a nightly-only experimental API. (pin_ergonomics)
Execute the destructor for this type, but different to Drop::drop, it requires self to be pinned. Read more
Source§

impl<T: Send + 'static, S: SlabStore<Item = WheelEntry<T>>> Send for TimerWheel<T, S>

Auto Trait Implementations§

§

impl<T, S = Slab<WheelEntry<T>>> !Freeze for TimerWheel<T, S>

§

impl<T, S = Slab<WheelEntry<T>>> !RefUnwindSafe for TimerWheel<T, S>

§

impl<T, S = Slab<WheelEntry<T>>> !Sync for TimerWheel<T, S>

§

impl<T, S = Slab<WheelEntry<T>>> !UnwindSafe for TimerWheel<T, S>

§

impl<T, S> Unpin for TimerWheel<T, S>
where S: Unpin, Vec<Level<T>>: Unpin,

§

impl<T, S> UnsafeUnpin for TimerWheel<T, S>
where S: UnsafeUnpin, Vec<Level<T>>: UnsafeUnpin,

Blanket Implementations§

Source§

impl<T> Any for T
where T: 'static + ?Sized,

Source§

fn type_id(&self) -> TypeId

Gets the TypeId of self. Read more
Source§

impl<T> Borrow<T> for T
where T: ?Sized,

Source§

fn borrow(&self) -> &T

Immutably borrows from an owned value. Read more
Source§

impl<T> BorrowMut<T> for T
where T: ?Sized,

Source§

fn borrow_mut(&mut self) -> &mut T

Mutably borrows from an owned value. Read more
Source§

impl<T> From<T> for T

Source§

fn from(t: T) -> T

Returns the argument unchanged.

Source§

impl<T, U> Into<U> for T
where U: From<T>,

Source§

fn into(self) -> U

Calls U::from(self).

That is, this conversion is whatever the implementation of From<T> for U chooses to do.

Source§

impl<T, U> TryFrom<U> for T
where U: Into<T>,

Source§

type Error = !

The type returned in the event of a conversion error.
Source§

fn try_from(value: U) -> Result<T, !>

Performs the conversion.
Source§

impl<T, U> TryInto<U> for T
where U: TryFrom<T>,

Source§

type Error = <U as TryFrom<T>>::Error

The type returned in the event of a conversion error.
Source§

fn try_into(self) -> Result<U, <U as TryFrom<T>>::Error>

Performs the conversion.