Wheel

Struct Wheel 

Source
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

Source

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 进行任务索引,具有代数安全特性。

Source

pub fn current_tick(&self) -> u64

Get current tick (L0 layer tick)

获取当前 tick(L0 层 tick)

Source

pub fn tick_duration(&self) -> Duration

Get tick duration (L0 layer tick duration)

获取 tick 持续时间(L0 层 tick 持续时间)

Source

pub fn slot_count(&self) -> usize

Get slot count (L0 layer slot count)

获取槽数量(L0 层槽数量)

Source

pub fn delay_to_ticks(&self, delay: Duration) -> u64

Calculate the number of ticks corresponding to the delay (based on L0 layer)

计算延迟对应的 tick 数量(基于 L0 层)

Source

pub fn allocate_handle(&mut self) -> TaskHandle

Allocate a handle from DeferredMap

从 DeferredMap 分配一个 handle

§Returns

A unique handle for later insertion

§返回值

用于后续插入的唯一 handle

Source

pub fn allocate_handles(&mut self, count: usize) -> Vec<TaskHandle>

Batch allocate handles from DeferredMap

从 DeferredMap 批量分配 handles

§Parameters
  • count: Number of handles to allocate
§Returns

Vector of unique handles for later batch insertion

§参数
  • count: 要分配的 handle 数量
§返回值

用于后续批量插入的唯一 handles 向量

Source

pub fn insert( &mut self, handle: TaskHandle, task: TimerTaskWithCompletionNotifier, )

Insert timer task

§Parameters
  • handle: Handle for the task
  • task: 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: 任务的 handle
  • task: 带完成通知器的定时器任务
§返回值

任务的唯一标识符(TaskId)- 现在从 DeferredMap 生成

§实现细节
  • 自动计算任务应该插入的层级和槽位
  • 分层模式:短延迟任务插入 L0,长延迟任务插入 L1
  • 使用位运算优化槽索引计算
  • 使用 DeferredMap 实现 O(1) 查找和取消,带代数检查
Source

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 tasks
  • tasks: List of timer tasks with completion notifiers
§Returns
  • Ok(()) if all tasks are successfully inserted
  • Err(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 实现高效的任务索引,具有代数安全特性
Source

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 实现安全的任务移除,带代数检查

Source

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 查找开销
  • 同一槽位的多个取消操作可以批量处理
  • 使用不稳定排序提高性能
  • 小批量优化:根据配置阈值跳过排序,直接处理
Source

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
Source

pub fn is_empty(&self) -> bool

Check if the timing wheel is empty

检查时间轮是否为空

Source

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 postpone
  • new_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: 要延期的任务 ID
  • new_delay: 新延迟时间(从当前 tick 重新计算,而非从原延迟时间继续)
  • new_callback: 新回调函数(如果为 None,则保留原回调)
§返回值

如果任务存在且成功延期则返回 true,否则返回 false

§实现细节
  • 从原层级/槽位移除任务,保留其 completion_notifier(不会触发取消通知)
  • 更新延迟时间和回调函数(如果提供)
  • 根据 new_delay 重新计算目标层级、槽位和轮数
  • 可能发生跨层迁移(L0 <-> L1)
  • 使用原始 TaskId 重新插入到新位置
  • 与外部持有的 TaskId 引用保持一致
Source

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 不存在,该任务将被跳过,不影响其他任务的延期
Source

pub fn postpone_batch_with_callbacks( &mut self, updates: Vec<(TaskId, Duration, Option<CallbackWrapper>)>, ) -> usize

Batch postpone timer tasks (replace callbacks)

§Parameters
  • updates: List of tuples of (task ID, new delay, new callback)
§Returns

Number of successfully postponed tasks

批量延期定时器任务(替换回调)

§参数
  • updates: (任务 ID, 新延迟, 新回调) 元组列表
§返回值

成功延期的任务数量

Auto Trait Implementations§

§

impl Freeze for Wheel

§

impl !RefUnwindSafe for Wheel

§

impl Send for Wheel

§

impl Sync for Wheel

§

impl Unpin for Wheel

§

impl !UnwindSafe for Wheel

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

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

fn try_from(value: U) -> Result<T, <T as TryFrom<U>>::Error>

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.