Crate kestrel_timer

Crate kestrel_timer 

Source
Expand description

§High-Performance Async Timer System

High-performance async timer based on Timing Wheel algorithm, supports tokio runtime

§Features

  • High Performance: Uses timing wheel algorithm, insert and delete operations are O(1)
  • Large-Scale Support: Efficiently manages 10000+ concurrent timers
  • Async Support: Based on tokio async runtime
  • Thread-Safe: Uses parking_lot for high-performance locking mechanism

§高性能异步定时器库

基于分层时间轮算法的高性能异步定时器库,支持 tokio 运行时

§特性

  • 高性能: 使用时间轮算法,插入和删除操作均为 O(1)
  • 大规模支持: 高效管理 10000+ 并发定时器
  • 异步支持: 基于 tokio 异步运行时
  • 线程安全: 使用 parking_lot 提供高性能的锁机制

§Quick Start (快速开始)

use kestrel_timer::{TimerWheel, CallbackWrapper, TimerTask};
use std::time::Duration;
use std::sync::Arc;

#[tokio::main]
async fn main() -> Result<(), Box<dyn std::error::Error>> {
    // Create timer manager (创建定时器管理器)
    let timer = TimerWheel::with_defaults();
     
    // Step 1: Create timer task (使用回调创建定时器任务)
    let callback = Some(CallbackWrapper::new(|| async {
        println!("Timer fired after 1 second!");
    }));
    let task = TimerTask::new_oneshot(Duration::from_secs(1), callback);
    let task_id = task.get_id();
     
    // Step 2: Register timer task and get completion notification (注册定时器任务并获取完成通知)
    let handle = timer.register(task);
     
    // Wait for timer completion (等待定时器完成)
    use kestrel_timer::CompletionReceiver;
    let (rx, _handle) = handle.into_parts();
    match rx {
        CompletionReceiver::OneShot(receiver) => {
            receiver.wait().await;
        },
        _ => {}
    }
    Ok(())
}

§English Architecture Description

§Timing Wheel Algorithm

Uses hierarchical timing wheel algorithm with L0 and L1 layers:

  • L0 Layer (Bottom): Handles short delay tasks

    • Slot count: Default 512, configurable, must be power of 2
    • Time precision: Default 10ms, configurable
    • Maximum time span: 5.12 seconds
  • L1 Layer (Upper): Handles long delay tasks

    • Slot count: Default 64, configurable, must be power of 2
    • Time precision: Default 1 second, configurable
    • Maximum time span: 64 seconds
  • Round Mechanism: Tasks beyond L1 range use round counting

§Performance Optimization

  • Uses parking_lot::Mutex instead of standard library Mutex for better performance
    • Uses FxHashMap (rustc-hash) instead of standard HashMap to reduce hash collisions
    • Slot count is power of 2, uses bitwise operations to optimize modulo
    • Task execution in separate tokio tasks to avoid blocking timing wheel advancement

§中文架构说明

§时间轮算法

采用分层时间轮(Hierarchical Timing Wheel)算法,包含 L0 和 L1 两层:

  • L0 层(底层): 处理短延迟任务

    • 槽位数量: 默认 512 个(可配置,必须是 2 的幂次方)
    • 时间精度: 默认 10ms(可配置)
    • 最大时间跨度: 5.12 秒
  • L1 层(高层): 处理长延迟任务

    • 槽位数量: 默认 64 个(可配置,必须是 2 的幂次方)
    • 时间精度: 默认 1 秒(可配置)
    • 最大时间跨度: 64 秒
  • 轮次机制: 超出 L1 层范围的任务使用轮次计数处理

§性能优化

  • 使用 parking_lot::Mutex 替代标准库的 Mutex,提供更好的性能
  • 使用 FxHashMap(rustc-hash)替代标准 HashMap,减少哈希冲突
  • 槽位数量为 2 的幂次方,使用位运算优化取模操作
  • 任务执行在独立的 tokio 任务中,避免阻塞时间轮推进

Re-exports§

pub use task::CallbackWrapper;
pub use task::TaskId;
pub use task::TimerTask;
pub use task::TaskCompletion;
pub use timer::handle::TimerHandle;
pub use timer::handle::TimerHandleWithCompletion;
pub use timer::handle::BatchHandle;
pub use timer::handle::BatchHandleWithCompletion;
pub use task::CompletionReceiver;
pub use timer::TimerWheel;

Modules§

config
Timer Configuration Module
error
task
timer
wheel

Structs§

TimerService
TimerService - timer service based on Actor pattern Manages multiple timer handles, listens to all timeout events, and aggregates notifications to be forwarded to the user.

Enums§

TaskNotification
Task notification type for distinguishing between one-shot and periodic tasks