Virtual-Clock Timer Scheduler (Rust)
Topics: scheduling, priority queue, binary heap, discrete-event simulation
Problem
Event loops and simulators don't sleep on real wall-clock time — they keep a queue of pending timers
and a virtual clock the caller advances explicitly. Build that scheduler.
pub struct Scheduler { /* ... */ }
impl Scheduler {
pub fn new() -> Self;
pub fn add(&mut self, id: &str, at: i64);
pub fn advance(&mut self, now: i64) -> Vec<String>;
}
add(id, at) schedules a timer to fire at virtual time at; the same id may be added multiple
times (each independent).
advance(now) moves the clock to now and returns every timer with fire time ≤ clock, in
fire-time order; same fire time → insertion order. Fired timers are removed (never refire).
- The clock only moves forward: if
now ≤ the current clock, the clock is unchanged.
- A timer added at or before the current clock is due immediately.
add(c,30) add(a,10) add(b,20)
advance(25) → [a, b]
advance(40) → [c]
Use a BinaryHeap. Since it's a max-heap, give Timer a reversed Ord keyed on (at, seq) so the
earliest timer is the "greatest" and pops first; advance keeps popping while the root is due.
Sign in to submit your solution.