Guide API
Skip to main content

Module timer

Module timer 

Source
Expand description

Injected clock and timer queue.

A TimerQueue holds pending one-shot and periodic timers; the event loop asks it which timers are due and how long until the next one. Time comes from an injected Clock: SystemClock in production, ManualClock in tests. Instant::now() is only called inside SystemClock — all timer logic operates on the opaque u64 millisecond values the clock yields, so tests can advance time deterministically without sleeps.

Two structural choices differ from the original:

  1. No re-entrancy dance. TimerQueue::collect_expired gathers due ids into a Vec and returns them; the caller dispatches afterwards, so there is no re-entrant mutation of the queue to guard against. Two invariants are preserved: a single now_ms value is used for the whole pass, and a periodic timer fires at most once per collect_expired call (even if overdue by several periods — it reschedules forward past now_ms via calc_next_expires_at).

  2. The clock lives in the event loop, not the queue. now_ms is passed into TimerQueue::collect_expired, TimerQueue::time_until_next, and TimerQueue::set_timer by the caller, which keeps the queue easy to test and gives set_timer the absolute expiry it needs for the reschedule grid arithmetic.

Guide: The event loop in depth.

§Turbo Vision heritage

Ports TTimerQueue (ttimerqu.cpp, system.h) and its time source THardwareInfo::getTickCountMs. The original marked each timer with a per-invocation collect-id so a callback could mutate the list mid-iteration, and stored the clock inside the queue; tvision-rs replaces the callback with a returned id list and injects the clock from the event loop (deviations D9 and D11).

Structs§

ManualClock
Test clock. Holds the current time in a Cell so &self can both read the time (via the Clock trait) and advance it (via set / advance).
SystemClock
Production clock. Captures an Instant at construction and returns elapsed ms on each call.
TimerId
A handle to a pending timer. Monotonically-increasing id allocated by TimerQueue; Copy + Eq + Hash so callers can store it and compare it in event handlers.
TimerQueue
A queue of pending one-shot and periodic timers.

Traits§

Clock
Monotonic millisecond clock.

Functions§

calc_next_expires_at
Catch-up-aware reschedule for periodic timers.