TimerWheel

Struct TimerWheel 

Source
pub struct TimerWheel { /* private fields */ }
Expand description

时间轮定时器管理器

Implementations§

Source§

impl TimerWheel

Source

pub fn new( tick_duration: Duration, slot_count: usize, ) -> Result<Self, TimerError>

创建新的定时器管理器

§参数
  • tick_duration: 每个 tick 的时间长度(建议 10ms)
  • slot_count: 槽位数量(必须是 2 的幂次方,建议 512 或 1024)
§返回
  • Ok(Self): 成功创建定时器管理器
  • Err(TimerError): 槽位数量无效
§示例
use kestrel_protocol_timer::TimerWheel;
use std::time::Duration;

#[tokio::main]
async fn main() {
    let timer = TimerWheel::new(Duration::from_millis(10), 512).unwrap();
}
Source

pub fn with_defaults() -> Result<Self, TimerError>

创建带默认配置的定时器管理器

  • tick 时长: 10ms
  • 槽位数量: 512
§返回
  • Ok(Self): 成功创建定时器管理器
  • Err(TimerError): 创建失败(不太可能,因为使用的是有效的默认值)
Source

pub fn create_service(&self) -> TimerService

创建与此时间轮绑定的 TimerService

§返回

绑定到此时间轮的 TimerService 实例

§示例
use kestrel_protocol_timer::TimerWheel;
use std::time::Duration;

#[tokio::main]
async fn main() {
    let timer = TimerWheel::with_defaults().unwrap();
    let mut service = timer.create_service();
     
    // 直接通过 service 批量调度定时器
    let callbacks: Vec<_> = (0..5)
        .map(|_| (Duration::from_millis(100), || async {}))
        .collect();
    service.schedule_once_batch(callbacks).await.unwrap();
     
    // 接收超时通知
    let mut rx = service.take_receiver().unwrap();
    while let Some(task_id) = rx.recv().await {
        println!("Task {:?} completed", task_id);
    }
}
Source

pub async fn schedule_once<C>( &self, delay: Duration, callback: C, ) -> Result<TimerHandle, TimerError>
where C: TimerCallback,

调度一次性定时器

§参数
  • delay: 延迟时间
  • callback: 实现了 TimerCallback trait 的回调对象
§返回
  • Ok(TimerHandle): 成功调度,返回定时器句柄,可用于取消定时器
  • Err(TimerError): 内部错误
§示例
use kestrel_protocol_timer::TimerWheel;
use std::time::Duration;
use std::sync::Arc;

#[tokio::main]
async fn main() {
    let timer = TimerWheel::with_defaults().unwrap();
     
    let handle = timer.schedule_once(Duration::from_secs(1), || async {
        println!("Timer fired!");
    }).await.unwrap();
     
    tokio::time::sleep(Duration::from_secs(2)).await;
}
Source

pub async fn schedule_once_batch<C>( &self, callbacks: Vec<(Duration, C)>, ) -> Result<BatchHandle, TimerError>
where C: TimerCallback,

批量调度一次性定时器

§参数
  • tasks: (延迟时间, 回调) 的元组列表
§返回
  • Ok(BatchHandle): 成功调度,返回批量定时器句柄
  • Err(TimerError): 内部错误
§性能优势
  • 批量处理减少锁竞争
  • 内部优化批量插入操作
  • 共享 Wheel 引用减少内存开销
§示例
use kestrel_protocol_timer::TimerWheel;
use std::time::Duration;
use std::sync::Arc;
use std::sync::atomic::{AtomicU32, Ordering};

#[tokio::main]
async fn main() {
    let timer = TimerWheel::with_defaults().unwrap();
    let counter = Arc::new(AtomicU32::new(0));
     
    // 动态生成批量回调
    let callbacks: Vec<(Duration, _)> = (0..3)
        .map(|i| {
            let counter = Arc::clone(&counter);
            let delay = Duration::from_millis(100 + i * 100);
            let callback = move || {
                let counter = Arc::clone(&counter);
                async move {
                    counter.fetch_add(1, Ordering::SeqCst);
                }
            };
            (delay, callback)
        })
        .collect();
     
    let batch = timer.schedule_once_batch(callbacks).await.unwrap();
    println!("Scheduled {} timers", batch.len());
     
    // 批量取消所有定时器
    let cancelled = batch.cancel_all();
    println!("Cancelled {} timers", cancelled);
}
Source

pub async fn schedule_once_notify( &self, delay: Duration, ) -> Result<TimerHandle, TimerError>

调度一次性通知定时器(无回调,仅通知)

§参数
  • delay: 延迟时间
§返回
  • Ok(TimerHandle): 成功调度,返回定时器句柄,可通过 into_completion_receiver() 获取通知接收器
  • Err(TimerError): 内部错误
§示例
use kestrel_protocol_timer::TimerWheel;
use std::time::Duration;

#[tokio::main]
async fn main() {
    let timer = TimerWheel::with_defaults().unwrap();
     
    let handle = timer.schedule_once_notify(Duration::from_secs(1)).await.unwrap();
     
    // 获取完成通知接收器
    handle.into_completion_receiver().0.await.ok();
    println!("Timer completed!");
}
Source

pub fn cancel(&self, task_id: TaskId) -> bool

取消定时器

§参数
  • task_id: 任务 ID
§返回

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

Source

pub fn cancel_batch(&self, task_ids: &[TaskId]) -> usize

批量取消定时器

§参数
  • task_ids: 要取消的任务 ID 列表
§返回

成功取消的任务数量

§性能优势
  • 批量处理减少锁竞争
  • 内部优化批量取消操作
§示例
use kestrel_protocol_timer::TimerWheel;
use std::time::Duration;

#[tokio::main]
async fn main() {
    let timer = TimerWheel::with_defaults().unwrap();
     
    // 创建多个定时器
    let handle1 = timer.schedule_once(Duration::from_secs(10), || async {}).await.unwrap();
    let handle2 = timer.schedule_once(Duration::from_secs(10), || async {}).await.unwrap();
    let handle3 = timer.schedule_once(Duration::from_secs(10), || async {}).await.unwrap();
     
    // 批量取消
    let task_ids = vec![handle1.task_id(), handle2.task_id(), handle3.task_id()];
    let cancelled = timer.cancel_batch(&task_ids);
    println!("已取消 {} 个定时器", cancelled);
}
Source

pub async fn shutdown(self)

停止定时器管理器

Trait Implementations§

Source§

impl Drop for TimerWheel

Source§

fn drop(&mut self)

Executes the destructor for this type. Read more

Auto Trait Implementations§

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.