TimerWheel

Struct TimerWheel 

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

时间轮定时器管理器 (Timing Wheel Timer Manager)

Implementations§

Source§

impl TimerWheel

Source

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

创建新的定时器管理器 (Create a new timer manager)

§参数 (Parameters)
  • config: 时间轮配置(已经过验证) (Timing wheel configuration, already validated)
§示例 (Examples)
use kestrel_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
    // (Use two-step 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

Create a timer manager with default configuration, hierarchical mode

  • L0 layer tick duration: 10ms, slot count: 512
  • L1 layer tick duration: 1s, slot count: 64
§参数 (Parameters)
  • config: 时间轮配置(已经过验证) (Timing wheel configuration, already validated)
§返回 (Returns)

定时器管理器实例 (Timer manager instance) (Timer manager instance)

§示例 (Examples)
use kestrel_timer::TimerWheel;

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

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

创建与此时间轮绑定的 TimerService(使用默认配置)(Create TimerService bound to this timing wheel with default configuration)

§返回 (Returns)

绑定到此时间轮的 TimerService 实例 (TimerService instance bound to this timing wheel)

§参数 (Parameters)
  • service_config: 服务配置 (Service configuration)
§示例 (Examples)
use kestrel_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(使用自定义配置) (Create TimerService bound to this timing wheel with custom configuration)

§参数 (Parameters)
  • config: 服务配置 (Service configuration)
§返回 (Returns)

绑定到此时间轮的 TimerService 实例 (TimerService instance bound to this timing wheel)

§示例 (Examples)
use kestrel_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

创建定时器任务(申请阶段)(Create timer task, application phase)

§参数 (Parameters)
  • delay: 延迟时间 (Delay duration)
  • callback: 实现了 TimerCallback trait 的回调对象 (Callback object implementing TimerCallback trait)
§返回 (Returns)

返回 TimerTask,需要通过 register() 注册到时间轮 (Returns TimerTask that needs to be registered to the timing wheel via register())

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

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

批量创建定时器任务(申请阶段) (Create batch of timer tasks, application phase)

§参数 (Parameters)
  • delays: 延迟时间列表 (Delay duration list)
§返回 (Returns)

返回 TimerTask 列表,需要通过 register_batch() 注册到时间轮 (Returns TimerTask list that needs to be registered to the timing wheel via register_batch())

§示例 (Examples)
use kestrel_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: 批量创建任务
    // (Create batch of tasks)
    let delays: Vec<Duration> = (0..3)
        .map(|_| Duration::from_millis(100))
        .collect();
     
    // 批量创建任务
    // (Create batch of tasks)
    let tasks = TimerWheel::create_batch(delays);
    println!("Created {} tasks", tasks.len());
     
    // 步骤 2: 批量注册任务
    // (Register batch of tasks)
    let batch = timer.register_batch(tasks);
}
Source

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

批量创建定时器任务(申请阶段,带回调) (Create batch of timer tasks, application phase, with callbacks)

§参数 (Parameters)
  • callbacks: (延迟时间, 回调) 的元组列表 (Tuple list of (delay duration, callback))
§返回 (Returns)

返回 TimerTask 列表,需要通过 register_batch() 注册到时间轮 (Returns TimerTask list that needs to be registered to the timing wheel via register_batch())

§示例 (Examples)
use kestrel_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: 批量创建任务
    // (Create batch of tasks)
    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();
     
    // 批量创建任务
    // (Create batch of tasks)
    let tasks = TimerWheel::create_batch_with_callbacks(callbacks);
    println!("Created {} tasks", tasks.len());
     
    // 步骤 2: 批量注册任务
    // (Register batch of tasks)
    let batch = timer.register_batch(tasks);
}
Source

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

注册定时器任务到时间轮(注册阶段) (Register timer task to timing wheel, registration phase)

§参数 (Parameters)
  • task: 通过 create_task() 创建的任务 (Task created via create_task())
§返回 (Returns)

返回定时器句柄,可用于取消定时器和接收完成通知 (Returns timer handle that can be used to cancel timer and receive completion notifications)

§示例 (Examples)
use kestrel_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();
     
    // 注册任务
    // (Register task)
    let handle = timer.register(task);
     
    // 等待定时器完成
    // (Wait for timer completion)
    handle.into_completion_receiver().0.await.ok();
}
Source

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

批量注册定时器任务到时间轮(注册阶段)(Batch register timer tasks to timing wheel, registration phase)

§参数 (Parameters)
  • tasks: 通过 create_batch() 创建的任务列表 (List of tasks created via create_batch())
§返回 (Returns)

返回批量定时器句柄 (Returns batch timer handle)

§示例 (Examples)
use kestrel_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

取消定时器 (Cancel timer)

§参数 (Parameters)
  • task_id: 任务 ID (Task ID)
§返回 (Returns)

如果任务存在且成功取消返回 true,否则返回 false (Returns true if task exists and is successfully cancelled, otherwise false)

§示例 (Examples)
use kestrel_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 取消
    // (Cancel task using task ID)
    let cancelled = timer.cancel(task_id);
    println!("Canceled successfully: {}", cancelled);
}
Source

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

批量取消定时器 (Batch cancel timers)

§参数 (Parameters)
  • task_ids: 要取消的任务 ID 列表 (List of task IDs to cancel)
§返回 (Returns)

成功取消的任务数量 (Number of successfully cancelled tasks)

§性能优势 (Performance Advantages)
  • 批量处理减少锁竞争 (Batch processing reduces lock contention)
  • 内部优化批量取消操作 (Internally optimized batch cancellation operation)
§示例 (Examples)
use kestrel_timer::{TimerWheel, TimerTask};
use std::time::Duration;

#[tokio::main]
async fn main() {
    let timer = TimerWheel::with_defaults();
     
    // 创建多个定时器
    // (Create multiple timers)
    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);
     
    // 批量取消
    // (Batch cancel)
    let cancelled = timer.cancel_batch(&task_ids);
    println!("Canceled {} timers", cancelled);
}
Source

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

推迟定时器 (Postpone timer)

§参数 (Parameters)
  • task_id: 要推迟的任务 ID (Task ID to postpone)
  • new_delay: 新的延迟时间(从当前时间点重新计算)(New delay duration, recalculated from current time)
  • callback: 新的回调函数,传入 None 保持原回调不变,传入 Some 替换为新回调 (New callback function, pass None to keep original callback, pass Some to replace with new callback)
§返回 (Returns)

如果任务存在且成功推迟返回 true,否则返回 false (Returns true if task exists and is successfully postponed, otherwise false)

§注意 (Note)
  • 推迟后任务 ID 保持不变 (Task ID remains unchanged after postponement)
  • 原有的 completion_receiver 仍然有效 (Original completion_receiver remains valid)
§示例 (Examples)
§保持原回调 (Keep original callback)
use kestrel_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 秒后触发(保持原回调)
    // (Postpone to 10 seconds after triggering, and keep original callback)
    let success = timer.postpone(task_id, Duration::from_secs(10), None);
    println!("Postponed successfully: {}", success);
}
§替换为新回调 (Replace with new callback)
use kestrel_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 秒后触发(并替换为新回调)
    // (Postpone to 10 seconds after triggering, and replace with new callback)
    let success = timer.postpone(task_id, Duration::from_secs(10), Some(CallbackWrapper::new(|| async {
        println!("New callback!");
    })));
    println!("Postponed successfully: {}", success);
}
Source

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

批量推迟定时器(保持原回调) (Batch postpone timers, keep original callbacks)

§参数 (Parameters)
  • updates: (任务ID, 新延迟) 的元组列表 (List of tuples of (task ID, new delay))
§返回 (Returns)

成功推迟的任务数量 (Number of successfully postponed tasks)

§注意 (Note)
  • 此方法会保持所有任务的原回调不变 (This method keeps all tasks’ original callbacks unchanged)
  • 如需替换回调,请使用 postpone_batch_with_callbacks (Use postpone_batch_with_callbacks if you need to replace callbacks)
§性能优势 (Performance Advantages)
  • 批量处理减少锁竞争 (Batch processing reduces lock contention)
  • 内部优化批量推迟操作 (Internally optimized batch postponement operation)
§示例 (Examples)
use kestrel_timer::{TimerWheel, TimerTask, CallbackWrapper};
use std::time::Duration;

#[tokio::main]
async fn main() {
    let timer = TimerWheel::with_defaults();
     
    // 创建多个带回调的定时器
    // (Create multiple tasks with callbacks)
    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);
     
    // 批量推迟(保持原回调)
    // (Batch postpone, keep original callbacks)
    let postponed = timer.postpone_batch(task_ids);
    println!("Postponed {} timers", postponed);
}
Source

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

批量推迟定时器(替换回调) (Batch postpone timers, replace callbacks)

§参数 (Parameters)
  • updates: (任务ID, 新延迟, 新回调) 的元组列表 (List of tuples of (task ID, new delay, new callback))
§返回 (Returns)

成功推迟的任务数量 (Number of successfully postponed tasks)

§性能优势 (Performance Advantages)
  • 批量处理减少锁竞争 (Batch processing reduces lock contention)
  • 内部优化批量推迟操作 (Internally optimized batch postponement operation)
§示例 (Examples)
use kestrel_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 {} timers", postponed);
}
Source

pub async fn shutdown(self)

停止定时器管理器 (Stop timer manager)

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.