English | 中文
C++ Hashed Hierarchical Wheel Timer, inspired by Folly HHWheelTimer. Header only, no dependencies.
Interactive visualization (teaching size: 4 layers × 8 slots). Open and try it:
(Same file can also be opened locally: docs/wheel_timer_demo.html — single file, no build, no external deps.)
The demo covers the four operations that match wheel_timer.h:
- Insert (Add / AddImpl):
delay_ms→end_tick; place bydiff = end_tick - expireTick_into layer 0..3; slot fromend_tickafter right-shift and mask; also writetimer_map_. - Trigger (Update): advance
expireTick_, pop timers due in the current layer-0 slot. - Cascade (CascadeTimers): when the layer-0 pointer wraps (
idx == 0), take timers from the matching higher-layer slot and re-AddImplthem (demote). - Delete (Del): look up by id in
timer_map_, swap-remove from the bucket vector, then erase the map entry.
Production parameters:
WHEEL_BUCKETS = 4,WHEEL_BITS = 8(256 slots per layer),DEFAULT_TICK_INTERVAL = 10ms. The demo uses a shrunk 8-slot wheel so cascades are easy to see; the math matches the source.
flowchart TB
subgraph L3["Layer 3 · slowest"]
B3["256 slots"]
end
subgraph L2["Layer 2"]
B2["256 slots"]
end
subgraph L1["Layer 1"]
B1["256 slots"]
end
subgraph L0["Layer 0 · fastest / Update scans"]
B0["256 slots · expireTick_ pointer"]
end
L3 -->|Cascade demote on wrap| L2
L2 -->|Cascade| L1
L1 -->|Cascade| L0
L0 -->|Fire due| Fire["Return expired ids"]
WheelTimer t;
// add two timer with 1000ms
auto t1 = t.Add(1000);
auto t2 = t.Add(1000);
// delete the second timer
t.Del(t2);
// wait for 1000ms; tick granularity is 10ms
std::this_thread::sleep_for(std::chrono::milliseconds(1000));
// update the timer, return the expired timers t1
auto ret = t.Update();
mkdir build
cd build
cmake ..
make