TimerWheel

Struct TimerWheel 

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

时间轮定时器管理器

Implementations§

Source§

impl TimerWheel

Source

pub fn new(config: WheelConfig, batch_config: BatchConfig) -> Self

创建新的定时器管理器

§参数
  • config: 时间轮配置(已经过验证)
§示例
use kestrel_protocol_timer::{TimerWheel, WheelConfig, TimerTask, BatchConfig};
use std::time::Duration;

#[tokio::main]
async fn main() {
    let config = WheelConfig::builder()
        .l0_tick_duration(Duration::from_millis(10))
        .l0_slot_count(512)
        .l1_tick_duration(Duration::from_secs(1))
        .l1_slot_count(64)
        .build()
        .unwrap();
    let timer = TimerWheel::new(config, BatchConfig::default());
     
    // 使用两步式 API
    let task = TimerWheel::create_task(Duration::from_secs(1), None);
    let handle = timer.register(task);
}
Source

pub fn with_defaults() -> Self

创建带默认配置的定时器管理器(分层模式)

  • L0 层 tick 时长: 10ms, 槽位数量: 512
  • L1 层 tick 时长: 1s, 槽位数量: 64
§示例
use kestrel_protocol_timer::TimerWheel;

#[tokio::main]
async fn main() {
    let timer = TimerWheel::with_defaults();
}
Source

pub fn create_service(&self, service_config: ServiceConfig) -> TimerService

创建与此时间轮绑定的 TimerService(使用默认配置)

§返回

绑定到此时间轮的 TimerService 实例

§参数
  • service_config: 服务配置
§示例
use kestrel_protocol_timer::{TimerWheel, TimerService, CallbackWrapper, ServiceConfig};
use std::time::Duration;
 

#[tokio::main]
async fn main() {
    let timer = TimerWheel::with_defaults();
    let mut service = timer.create_service(ServiceConfig::default());
     
    // 使用两步式 API 通过 service 批量调度定时器
    let callbacks: Vec<(Duration, Option<CallbackWrapper>)> = (0..5)
        .map(|_| (Duration::from_millis(100), Some(CallbackWrapper::new(|| async {}))))
        .collect();
    let tasks = TimerService::create_batch_with_callbacks(callbacks);
    service.register_batch(tasks).unwrap();
     
    // 接收超时通知
    let mut rx = service.take_receiver().unwrap();
    while let Some(task_id) = rx.recv().await {
        println!("Task {:?} completed", task_id);
    }
}
Source

pub fn create_service_with_config(&self, config: ServiceConfig) -> TimerService

创建与此时间轮绑定的 TimerService(使用自定义配置)

§参数
  • config: 服务配置
§返回

绑定到此时间轮的 TimerService 实例

§示例
use kestrel_protocol_timer::{TimerWheel, ServiceConfig};

#[tokio::main]
async fn main() {
    let timer = TimerWheel::with_defaults();
    let config = ServiceConfig::builder()
        .command_channel_capacity(1024)
        .timeout_channel_capacity(2000)
        .build()
        .unwrap();
    let service = timer.create_service_with_config(config);
}
Source

pub fn create_task( delay: Duration, callback: Option<CallbackWrapper>, ) -> TimerTask

创建定时器任务(申请阶段)

§参数
  • delay: 延迟时间
  • callback: 实现了 TimerCallback trait 的回调对象
§返回

返回 TimerTask,需要通过 register() 注册到时间轮

§示例
use kestrel_protocol_timer::{TimerWheel, TimerTask, CallbackWrapper};
use std::time::Duration;
 
 
#[tokio::main]
async fn main() {
    let timer = TimerWheel::with_defaults();
     
    // 步骤 1: 创建任务
    let task = TimerWheel::create_task(Duration::from_secs(1), Some(CallbackWrapper::new(|| async {
        println!("Timer fired!");
    })));
     
    // 获取任务 ID
    let task_id = task.get_id();
    println!("Created task: {:?}", task_id);
     
    // 步骤 2: 注册任务
    let handle = timer.register(task);
}
Source

pub fn create_batch(delays: Vec<Duration>) -> Vec<TimerTask>

批量创建定时器任务(申请阶段)

§参数
  • callbacks: (延迟时间, 回调) 的元组列表
§返回

返回 TimerTask 列表,需要通过 register_batch() 注册到时间轮

§示例
use kestrel_protocol_timer::{TimerWheel, TimerTask, CallbackWrapper};
use std::time::Duration;
use std::sync::Arc;
use std::sync::atomic::{AtomicU32, Ordering};
 
#[tokio::main]
async fn main() {
    let timer = TimerWheel::with_defaults();
    let counter = Arc::new(AtomicU32::new(0));
     
    // 步骤 1: 批量创建任务
    let delays: Vec<Duration> = (0..3)
        .map(|_| Duration::from_millis(100))
        .collect();
     
    let tasks = TimerWheel::create_batch(delays);
    println!("Created {} tasks", tasks.len());
     
    // 步骤 2: 批量注册任务
    let batch = timer.register_batch(tasks);
}
Source

pub fn create_batch_with_callbacks( callbacks: Vec<(Duration, Option<CallbackWrapper>)>, ) -> Vec<TimerTask>

批量创建定时器任务(申请阶段)

§参数
  • callbacks: (延迟时间, 回调) 的元组列表
§返回

返回 TimerTask 列表,需要通过 register_batch() 注册到时间轮

§示例
use kestrel_protocol_timer::{TimerWheel, TimerTask, CallbackWrapper};
use std::time::Duration;
use std::sync::Arc;
use std::sync::atomic::{AtomicU32, Ordering};
 
#[tokio::main]
async fn main() {
    let timer = TimerWheel::with_defaults();
    let counter = Arc::new(AtomicU32::new(0));
     
    // 步骤 1: 批量创建任务
    let delays: Vec<Duration> = (0..3)
        .map(|_| Duration::from_millis(100))
        .collect();
    let callbacks: Vec<(Duration, Option<CallbackWrapper>)> = delays
        .into_iter()
        .map(|delay| {
            let counter = Arc::clone(&counter);
            let callback = Some(CallbackWrapper::new(move || {
                let counter = Arc::clone(&counter);
                async move {
                    counter.fetch_add(1, Ordering::SeqCst);
                }
            }));
            (delay, callback)
        })
        .collect();
     
    let tasks = TimerWheel::create_batch_with_callbacks(callbacks);
    println!("Created {} tasks", tasks.len());
     
    // 步骤 2: 批量注册任务
    let batch = timer.register_batch(tasks);
}
Source

pub fn register(&self, task: TimerTask) -> TimerHandle

注册定时器任务到时间轮(注册阶段)

§参数
  • task: 通过 create_task() 创建的任务
§返回

返回定时器句柄,可用于取消定时器和接收完成通知

§示例
use kestrel_protocol_timer::{TimerWheel, TimerTask, CallbackWrapper};
 
use std::time::Duration;
 
#[tokio::main]
async fn main() {
    let timer = TimerWheel::with_defaults();
     
    let task = TimerWheel::create_task(Duration::from_secs(1), Some(CallbackWrapper::new(|| async {
        println!("Timer fired!");
    })));
    let task_id = task.get_id();
     
    let handle = timer.register(task);
     
    // 等待定时器完成
    handle.into_completion_receiver().0.await.ok();
}
Source

pub fn register_batch(&self, tasks: Vec<TimerTask>) -> BatchHandle

批量注册定时器任务到时间轮(注册阶段)

§参数
  • tasks: 通过 create_batch() 创建的任务列表
§返回

返回批量定时器句柄

§示例
use kestrel_protocol_timer::{TimerWheel, TimerTask};
use std::time::Duration;
 
#[tokio::main]
async fn main() {
    let timer = TimerWheel::with_defaults();
     
    let delays: Vec<Duration> = (0..3)
        .map(|_| Duration::from_secs(1))
        .collect();
    let tasks = TimerWheel::create_batch(delays);
     
    let batch = timer.register_batch(tasks);
    println!("Registered {} timers", batch.len());
}
Source

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

取消定时器

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

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

§示例
use kestrel_protocol_timer::{TimerWheel, TimerTask, CallbackWrapper};
 
use std::time::Duration;

#[tokio::main]
async fn main() {
    let timer = TimerWheel::with_defaults();
     
    let task = TimerWheel::create_task(Duration::from_secs(10), Some(CallbackWrapper::new(|| async {
        println!("Timer fired!");
    })));
    let task_id = task.get_id();
    let _handle = timer.register(task);
     
    // 使用任务 ID 取消
    let cancelled = timer.cancel(task_id);
    println!("取消成功: {}", cancelled);
}
Source

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

批量取消定时器

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

成功取消的任务数量

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

#[tokio::main]
async fn main() {
    let timer = TimerWheel::with_defaults();
     
    // 创建多个定时器
    let task1 = TimerWheel::create_task(Duration::from_secs(10), None);
    let task2 = TimerWheel::create_task(Duration::from_secs(10), None);
    let task3 = TimerWheel::create_task(Duration::from_secs(10), None);
     
    let task_ids = vec![task1.get_id(), task2.get_id(), task3.get_id()];
     
    let _h1 = timer.register(task1);
    let _h2 = timer.register(task2);
    let _h3 = timer.register(task3);
     
    // 批量取消
    let cancelled = timer.cancel_batch(&task_ids);
    println!("已取消 {} 个定时器", cancelled);
}
Source

pub fn postpone( &self, task_id: TaskId, new_delay: Duration, callback: Option<CallbackWrapper>, ) -> bool

推迟定时器

§参数
  • task_id: 要推迟的任务 ID
  • new_delay: 新的延迟时间(从当前时间点重新计算)
  • callback: 新的回调函数,传入 None 保持原回调不变,传入 Some 替换为新回调
§返回

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

§注意
  • 推迟后任务 ID 保持不变
  • 原有的 completion_receiver 仍然有效
§示例
§保持原回调
use kestrel_protocol_timer::{TimerWheel, TimerTask, CallbackWrapper};
use std::time::Duration;
 

#[tokio::main]
async fn main() {
    let timer = TimerWheel::with_defaults();
     
    let task = TimerWheel::create_task(Duration::from_secs(5), Some(CallbackWrapper::new(|| async {
        println!("Timer fired!");
    })));
    let task_id = task.get_id();
    let _handle = timer.register(task);
     
    // 推迟到 10 秒后触发(保持原回调)
    let success = timer.postpone(task_id, Duration::from_secs(10), None);
    println!("推迟成功: {}", success);
}
§替换为新回调
use kestrel_protocol_timer::{TimerWheel, TimerTask, CallbackWrapper};
use std::time::Duration;

#[tokio::main]
async fn main() {
    let timer = TimerWheel::with_defaults();
     
    let task = TimerWheel::create_task(Duration::from_secs(5), Some(CallbackWrapper::new(|| async {
        println!("Original callback!");
    })));
    let task_id = task.get_id();
    let _handle = timer.register(task);
     
    // 推迟到 10 秒后触发(并替换为新回调)
    let success = timer.postpone(task_id, Duration::from_secs(10), Some(CallbackWrapper::new(|| async {
        println!("New callback!");
    })));
    println!("推迟成功: {}", success);
}
Source

pub fn postpone_batch(&self, updates: Vec<(TaskId, Duration)>) -> usize

批量推迟定时器(保持原回调)

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

成功推迟的任务数量

§注意
  • 此方法会保持所有任务的原回调不变
  • 如需替换回调,请使用 postpone_batch_with_callbacks
§性能优势
  • 批量处理减少锁竞争
  • 内部优化批量推迟操作
§示例
use kestrel_protocol_timer::{TimerWheel, TimerTask, CallbackWrapper};
use std::time::Duration;

#[tokio::main]
async fn main() {
    let timer = TimerWheel::with_defaults();
     
    // 创建多个带回调的定时器
    let task1 = TimerWheel::create_task(Duration::from_secs(5), Some(CallbackWrapper::new(|| async {
        println!("Task 1 fired!");
    })));
    let task2 = TimerWheel::create_task(Duration::from_secs(5), Some(CallbackWrapper::new(|| async {
        println!("Task 2 fired!");
    })));
    let task3 = TimerWheel::create_task(Duration::from_secs(5), Some(CallbackWrapper::new(|| async {
        println!("Task 3 fired!");
    })));
     
    let task_ids = vec![
        (task1.get_id(), Duration::from_secs(10)),
        (task2.get_id(), Duration::from_secs(15)),
        (task3.get_id(), Duration::from_secs(20)),
    ];
     
    timer.register(task1);
    timer.register(task2);
    timer.register(task3);
     
    // 批量推迟(保持原回调)
    let postponed = timer.postpone_batch(task_ids);
    println!("已推迟 {} 个定时器", postponed);
}
Source

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

批量推迟定时器(替换回调)

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

成功推迟的任务数量

§性能优势
  • 批量处理减少锁竞争
  • 内部优化批量推迟操作
§示例
use kestrel_protocol_timer::{TimerWheel, TimerTask, CallbackWrapper};
use std::time::Duration;
use std::sync::Arc;
use std::sync::atomic::{AtomicU32, Ordering};

#[tokio::main]
async fn main() {
    let timer = TimerWheel::with_defaults();
    let counter = Arc::new(AtomicU32::new(0));
     
    // 创建多个定时器
    let task1 = TimerWheel::create_task(Duration::from_secs(5), None);
    let task2 = TimerWheel::create_task(Duration::from_secs(5), None);
     
    let id1 = task1.get_id();
    let id2 = task2.get_id();
     
    timer.register(task1);
    timer.register(task2);
     
    // 批量推迟并替换回调
    let updates: Vec<_> = vec![id1, id2]
        .into_iter()
        .map(|id| {
            let counter = Arc::clone(&counter);
            (id, Duration::from_secs(10), Some(CallbackWrapper::new(move || {
                let counter = Arc::clone(&counter);
                async move { counter.fetch_add(1, Ordering::SeqCst); }
            })))
        })
        .collect();
    let postponed = timer.postpone_batch_with_callbacks(updates);
    println!("已推迟 {} 个定时器", postponed);
}
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.