pub struct Wheel { /* private fields */ }Expand description
Timing wheel data structure (hierarchical mode)
Now uses DeferredMap for O(1) task lookup and generational safety.
时间轮数据结构(分层模式)
现在使用 DeferredMap 实现 O(1) 任务查找和代数安全
Implementations§
Source§impl Wheel
impl Wheel
Sourcepub fn new(config: WheelConfig, batch_config: BatchConfig) -> Self
pub fn new(config: WheelConfig, batch_config: BatchConfig) -> Self
Create new timing wheel
§Parameters
config: Timing wheel configuration (already validated)batch_config: Batch processing configuration
§Notes
Configuration parameters have been validated in WheelConfig::builder().build(), so this method will not fail. Now uses DeferredMap for task indexing with generational safety.
创建新的时间轮
§参数
config: 时间轮配置(已验证)batch_config: 批处理配置
§注意
配置参数已在 WheelConfig::builder().build() 中验证,因此此方法不会失败。 现在使用 DeferredMap 进行任务索引,具有代数安全特性。
Sourcepub fn current_tick(&self) -> u64
pub fn current_tick(&self) -> u64
Get current tick (L0 layer tick)
获取当前 tick(L0 层 tick)
Sourcepub fn tick_duration(&self) -> Duration
pub fn tick_duration(&self) -> Duration
Get tick duration (L0 layer tick duration)
获取 tick 持续时间(L0 层 tick 持续时间)
Sourcepub fn slot_count(&self) -> usize
pub fn slot_count(&self) -> usize
Get slot count (L0 layer slot count)
获取槽数量(L0 层槽数量)
Sourcepub fn delay_to_ticks(&self, delay: Duration) -> u64
pub fn delay_to_ticks(&self, delay: Duration) -> u64
Calculate the number of ticks corresponding to the delay (based on L0 layer)
计算延迟对应的 tick 数量(基于 L0 层)
Sourcepub fn allocate_handle(&mut self) -> TaskHandle
pub fn allocate_handle(&mut self) -> TaskHandle
Sourcepub fn allocate_handles(&mut self, count: usize) -> Vec<TaskHandle>
pub fn allocate_handles(&mut self, count: usize) -> Vec<TaskHandle>
Sourcepub fn insert(
&mut self,
handle: TaskHandle,
task: TimerTaskWithCompletionNotifier,
)
pub fn insert( &mut self, handle: TaskHandle, task: TimerTaskWithCompletionNotifier, )
Insert timer task
§Parameters
handle: Handle for the tasktask: Timer task with completion notifier
§Returns
Unique identifier of the task (TaskId) - now generated from DeferredMap
§Implementation Details
- Allocates Handle from DeferredMap to generate TaskId with generational safety
- Automatically calculate the layer and slot where the task should be inserted
- Hierarchical mode: short delay tasks are inserted into L0, long delay tasks are inserted into L1
- Use bit operations to optimize slot index calculation
- Use DeferredMap for O(1) lookup and cancellation with generation checking
插入定时器任务
§参数
handle: 任务的 handletask: 带完成通知器的定时器任务
§返回值
任务的唯一标识符(TaskId)- 现在从 DeferredMap 生成
§实现细节
- 自动计算任务应该插入的层级和槽位
- 分层模式:短延迟任务插入 L0,长延迟任务插入 L1
- 使用位运算优化槽索引计算
- 使用 DeferredMap 实现 O(1) 查找和取消,带代数检查
Sourcepub fn insert_batch(
&mut self,
handles: Vec<TaskHandle>,
tasks: Vec<TimerTaskWithCompletionNotifier>,
) -> Result<(), TimerError>
pub fn insert_batch( &mut self, handles: Vec<TaskHandle>, tasks: Vec<TimerTaskWithCompletionNotifier>, ) -> Result<(), TimerError>
Batch insert timer tasks
§Parameters
handles: List of pre-allocated handles for taskstasks: List of timer tasks with completion notifiers
§Returns
Ok(())if all tasks are successfully insertedErr(TimerError::BatchLengthMismatch)if handles and tasks lengths don’t match
§Performance Advantages
- Reduce repeated boundary checks and capacity adjustments
- For tasks with the same delay, calculation results can be reused
- Uses DeferredMap for efficient task indexing with generational safety
批量插入定时器任务
§参数
handles: 任务的预分配 handles 列表tasks: 带完成通知器的定时器任务列表
§返回值
Ok(())如果所有任务成功插入Err(TimerError::BatchLengthMismatch)如果 handles 和 tasks 长度不匹配
§性能优势
- 减少重复的边界检查和容量调整
- 对于相同延迟的任务,可以重用计算结果
- 使用 DeferredMap 实现高效的任务索引,具有代数安全特性
Sourcepub fn cancel(&mut self, task_id: TaskId) -> bool
pub fn cancel(&mut self, task_id: TaskId) -> bool
Cancel timer task
§Parameters
task_id: Task ID
§Returns
Returns true if the task exists and is successfully cancelled, otherwise returns false
Now uses DeferredMap for safe task removal with generational checking
取消定时器任务
§参数
task_id: 任务 ID
§返回值
如果任务存在且成功取消则返回 true,否则返回 false
现在使用 DeferredMap 实现安全的任务移除,带代数检查
Sourcepub fn cancel_batch(&mut self, task_ids: &[TaskId]) -> usize
pub fn cancel_batch(&mut self, task_ids: &[TaskId]) -> usize
Batch cancel timer tasks
§Parameters
task_ids: List of task IDs to cancel
§Returns
Number of successfully cancelled tasks
§Performance Advantages
- Reduce repeated HashMap lookup overhead
- Multiple cancellation operations on the same slot can be batch processed
- Use unstable sort to improve performance
- Small batch optimization: skip sorting based on configuration threshold, process directly
批量取消定时器任务
§参数
task_ids: 要取消的任务 ID 列表
§返回值
成功取消的任务数量
§性能优势
- 减少重复的 HashMap 查找开销
- 同一槽位的多个取消操作可以批量处理
- 使用不稳定排序提高性能
- 小批量优化:根据配置阈值跳过排序,直接处理
Sourcepub fn advance(&mut self) -> Vec<WheelAdvanceResult>
pub fn advance(&mut self) -> Vec<WheelAdvanceResult>
Advance the timing wheel by one tick, return all expired tasks
§Returns
List of expired tasks
§Implementation Details
- L0 layer advances 1 tick each time (no rounds check)
- L1 layer advances once every (L1_tick / L0_tick) times
- L1 expired tasks are batch demoted to L0
推进时间轮一个 tick,返回所有过期的任务
§返回值
过期任务列表
§实现细节
- L0 层每次推进 1 个 tick(无轮数检查)
- L1 层每 (L1_tick / L0_tick) 次推进一次
- L1 层过期任务批量降级到 L0
Sourcepub fn postpone(
&mut self,
task_id: TaskId,
new_delay: Duration,
new_callback: Option<CallbackWrapper>,
) -> bool
pub fn postpone( &mut self, task_id: TaskId, new_delay: Duration, new_callback: Option<CallbackWrapper>, ) -> bool
Postpone timer task (keep original TaskId)
§Parameters
task_id: Task ID to postponenew_delay: New delay time (recalculated from current tick, not continuing from original delay time)new_callback: New callback function (if None, keep original callback)
§Returns
Returns true if the task exists and is successfully postponed, otherwise returns false
§Implementation Details
- Remove task from original layer/slot, keep its completion_notifier (will not trigger cancellation notification)
- Update delay time and callback function (if provided)
- Recalculate target layer, slot, and rounds based on new_delay
- Cross-layer migration may occur (L0 <-> L1)
- Re-insert to new position using original TaskId
- Keep consistent with external held TaskId reference
延期定时器任务(保留原始 TaskId)
§参数
task_id: 要延期的任务 IDnew_delay: 新延迟时间(从当前 tick 重新计算,而非从原延迟时间继续)new_callback: 新回调函数(如果为 None,则保留原回调)
§返回值
如果任务存在且成功延期则返回 true,否则返回 false
§实现细节
- 从原层级/槽位移除任务,保留其 completion_notifier(不会触发取消通知)
- 更新延迟时间和回调函数(如果提供)
- 根据 new_delay 重新计算目标层级、槽位和轮数
- 可能发生跨层迁移(L0 <-> L1)
- 使用原始 TaskId 重新插入到新位置
- 与外部持有的 TaskId 引用保持一致
Sourcepub fn postpone_batch(&mut self, updates: Vec<(TaskId, Duration)>) -> usize
pub fn postpone_batch(&mut self, updates: Vec<(TaskId, Duration)>) -> usize
Batch postpone timer tasks
§Parameters
updates: List of tuples of (task ID, new delay)
§Returns
Number of successfully postponed tasks
§Performance Advantages
- Batch processing reduces function call overhead
- All delays are recalculated from current_tick at call time
§Notes
- If a task ID does not exist, that task will be skipped without affecting other tasks’ postponement
批量延期定时器任务
§参数
updates: (任务 ID, 新延迟) 元组列表
§返回值
成功延期的任务数量
§性能优势
- 批处理减少函数调用开销
- 所有延迟在调用时从 current_tick 重新计算
§注意
- 如果任务 ID 不存在,该任务将被跳过,不影响其他任务的延期