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

创建新的定时器管理器

§参数
  • config: 时间轮配置,已验证
§Examples (示例)
use kestrel_timer::{TimerWheel, config::WheelConfig, TimerTask, config::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());
     
    // Use two-step 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

Create 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

使用默认配置创建定时器管理器,分层模式

  • L0 层 tick 持续时间:10ms,槽数量:512
  • L1 层 tick 持续时间:1s,槽数量:64
§参数
  • config: 时间轮配置,已验证
§返回值

定时器管理器实例

§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

Create TimerService bound to this timing wheel with default configuration

§Parameters
  • service_config: Service configuration
§Returns

TimerService instance bound to this timing wheel

创建绑定到此时间轮的 TimerService,使用默认配置

§参数
  • service_config: 服务配置
§返回值

绑定到此时间轮的 TimerService 实例

§Examples (示例)
use kestrel_timer::{TimerWheel, TimerService, CallbackWrapper, config::ServiceConfig};
use std::time::Duration;
 

#[tokio::main]
async fn main() {
    let timer = TimerWheel::with_defaults();
    let mut service = timer.create_service(ServiceConfig::default());
     
    // Use two-step API to batch schedule timers through service
    // 使用两步 API 通过服务批量调度定时器
    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();
     
    // Receive timeout notifications
    // 接收超时通知
    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

Create TimerService bound to this timing wheel with custom configuration

§Parameters
  • config: Service configuration
§Returns

TimerService instance bound to this timing wheel

创建绑定到此时间轮的 TimerService,使用自定义配置

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

绑定到此时间轮的 TimerService 实例

§Examples (示例)
use kestrel_timer::{TimerWheel, config::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 (static method, apply stage)

§Parameters
  • delay: Delay duration
  • callback: Callback object implementing TimerCallback trait
§Returns

Return TimerTask, needs to be registered through register()

创建定时器任务 (静态方法,应用阶段)

§参数
  • delay: 延迟时间
  • callback: 回调对象,实现 TimerCallback 特质
§返回值

返回 TimerTask,需要通过 register() 注册

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

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

Create batch of timer tasks (static method, apply stage, no callbacks)

§Parameters
  • delays: List of delay times
§Returns

Return TimerTask list, needs to be registered through register_batch()

创建定时器任务 (静态方法,应用阶段,没有回调)

§参数
  • delays: 延迟时间列表
§返回值

返回 TimerTask 列表,需要通过 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));
     
    // Step 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());
     
    // Step 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 (static method, apply stage, with callbacks)

§Parameters
  • callbacks: List of tuples of (delay time, callback)
§Returns

Return TimerTask list, needs to be registered through register_batch()

创建定时器任务 (静态方法,应用阶段,有回调)

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

返回 TimerTask 列表,需要通过 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));
     
    // Step 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());
     
    // Step 2: Register batch of tasks
    // 注册批量任务
    let batch = timer.register_batch(tasks);
}
Source

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

Register timer task to timing wheel (registration phase)

§Parameters
  • task: Task created via create_task()
§Returns

Return timer handle with completion receiver that can be used to cancel timer and receive completion notifications

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

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

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

§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
    // 等待定时器完成
    let (rx, _handle) = handle.into_parts();
    rx.0.await.ok();
}
Source

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

Batch register timer tasks to timing wheel (registration phase)

§Parameters
  • tasks: List of tasks created via create_batch()
§Returns

Return batch timer handle with completion receivers

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

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

返回包含完成通知接收器的批量定时器句柄

§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: Task ID
§Returns

Returns true if task exists and is successfully cancelled, otherwise false

取消定时器

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

如果任务存在且成功取消则返回 true,否则返回 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);
     
    // Cancel task using task ID
    // 使用任务 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: List of task IDs to cancel
§Returns

Number of successfully cancelled tasks

批量取消定时器

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

成功取消的任务数量

§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: Task ID to postpone
  • new_delay: New delay duration, recalculated from current time
  • callback: New callback function, pass None to keep original callback, pass Some to replace with new callback
§Returns

Returns true if task exists and is successfully postponed, otherwise false

推迟定时器

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

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

§Note
  • Task ID remains unchanged after postponement
  • Original completion_receiver remains valid
§注意
  • 任务 ID 在推迟后保持不变
  • 原始 completion_receiver 保持有效
§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);
     
    // Postpone to 10 seconds after triggering, and keep original callback
    // 推迟到 10 秒后触发,并保持原始回调
    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);
     
    // Postpone to 10 seconds after triggering, and replace with new callback
    // 推迟到 10 秒后触发,并替换为新的回调
    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: List of tuples of (task ID, new delay)
§Returns

Number of successfully postponed tasks

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

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

成功推迟的任务数量

§Note
  • This method keeps all tasks’ original callbacks unchanged
  • Use postpone_batch_with_callbacks if you need to replace callbacks
§注意
  • 此方法保持所有任务的原始回调不变
  • 如果需要替换回调,请使用 postpone_batch_with_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: List of tuples of (task ID, new delay, new callback)
§Returns

Number of successfully postponed tasks

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

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

成功推迟的任务数量

§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));
     
    // Create multiple timers
    // 创建多个定时器
    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);
     
    // Batch postpone and replace callbacks
    // 批量推迟并替换回调
    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)

Graceful shutdown of TimerWheel

优雅关闭 TimerWheel

§Examples (示例)
let timer = TimerWheel::with_defaults();
 
// Use timer... (使用定时器...)
 
timer.shutdown().await;

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.