pub struct TimerWheel { /* private fields */ }Expand description
时间轮定时器管理器
Implementations§
Source§impl TimerWheel
impl TimerWheel
Sourcepub fn new(config: WheelConfig) -> Self
pub fn new(config: WheelConfig) -> Self
创建新的定时器管理器
§参数
config: 时间轮配置(已经过验证)
§示例
use kestrel_protocol_timer::{TimerWheel, WheelConfig, TimerTask};
use std::time::Duration;
#[tokio::main]
async fn main() {
let config = WheelConfig::builder()
.tick_duration(Duration::from_millis(10))
.slot_count(512)
.build()
.unwrap();
let timer = TimerWheel::new(config);
// 使用两步式 API
let task = TimerWheel::create_task(Duration::from_secs(1), || async {});
let handle = timer.register(task);
}Sourcepub fn with_defaults() -> Self
pub fn with_defaults() -> Self
创建带默认配置的定时器管理器
- tick 时长: 10ms
- 槽位数量: 512
§示例
use kestrel_protocol_timer::TimerWheel;
#[tokio::main]
async fn main() {
let timer = TimerWheel::with_defaults();
}Sourcepub fn create_service(&self) -> TimerService
pub fn create_service(&self) -> TimerService
创建与此时间轮绑定的 TimerService(使用默认配置)
§返回
绑定到此时间轮的 TimerService 实例
§示例
use kestrel_protocol_timer::{TimerWheel, TimerService};
use std::time::Duration;
#[tokio::main]
async fn main() {
let timer = TimerWheel::with_defaults();
let mut service = timer.create_service();
// 使用两步式 API 通过 service 批量调度定时器
let tasks = TimerService::create_batch(
(0..5).map(|_| (Duration::from_millis(100), || async {})).collect()
);
service.register_batch(tasks).await;
// 接收超时通知
let mut rx = service.take_receiver().unwrap();
while let Some(task_id) = rx.recv().await {
println!("Task {:?} completed", task_id);
}
}Sourcepub fn create_service_with_config(&self, config: ServiceConfig) -> TimerService
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);
}Sourcepub fn create_task<C>(delay: Duration, callback: C) -> TimerTaskwhere
C: TimerCallback,
pub fn create_task<C>(delay: Duration, callback: C) -> TimerTaskwhere
C: TimerCallback,
创建定时器任务(申请阶段)
§参数
delay: 延迟时间callback: 实现了 TimerCallback trait 的回调对象
§返回
返回 TimerTask,需要通过 register() 注册到时间轮
§示例
use kestrel_protocol_timer::{TimerWheel, TimerTask};
use std::time::Duration;
#[tokio::main]
async fn main() {
let timer = TimerWheel::with_defaults();
// 步骤 1: 创建任务
let task = TimerWheel::create_task(Duration::from_secs(1), || async {
println!("Timer fired!");
});
// 获取任务 ID
let task_id = task.get_id();
println!("Created task: {:?}", task_id);
// 步骤 2: 注册任务
let handle = timer.register(task);
}Sourcepub fn create_batch<C>(callbacks: Vec<(Duration, C)>) -> Vec<TimerTask>where
C: TimerCallback,
pub fn create_batch<C>(callbacks: Vec<(Duration, C)>) -> Vec<TimerTask>where
C: TimerCallback,
批量创建定时器任务(申请阶段)
§参数
callbacks: (延迟时间, 回调) 的元组列表
§返回
返回 TimerTask 列表,需要通过 register_batch() 注册到时间轮
§示例
use kestrel_protocol_timer::{TimerWheel, TimerTask};
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 callbacks: Vec<_> = (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 tasks = TimerWheel::create_batch(callbacks);
println!("Created {} tasks", tasks.len());
// 步骤 2: 批量注册任务
let batch = timer.register_batch(tasks);
}Sourcepub fn register(&self, task: TimerTask) -> TimerHandle
pub fn register(&self, task: TimerTask) -> TimerHandle
注册定时器任务到时间轮(注册阶段)
§参数
task: 通过create_task()创建的任务
§返回
返回定时器句柄,可用于取消定时器和接收完成通知
§示例
use kestrel_protocol_timer::{TimerWheel, TimerTask};
use std::time::Duration;
#[tokio::main]
async fn main() {
let timer = TimerWheel::with_defaults();
let task = TimerWheel::create_task(Duration::from_secs(1), || async {
println!("Timer fired!");
});
let task_id = task.get_id();
let handle = timer.register(task);
// 等待定时器完成
handle.into_completion_receiver().0.await.ok();
}Sourcepub fn register_batch(&self, tasks: Vec<TimerTask>) -> BatchHandle
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 callbacks: Vec<_> = (0..3)
.map(|_| (Duration::from_secs(1), || async {}))
.collect();
let tasks = TimerWheel::create_batch(callbacks);
let batch = timer.register_batch(tasks);
println!("Registered {} timers", batch.len());
}Sourcepub fn cancel(&self, task_id: TaskId) -> bool
pub fn cancel(&self, task_id: TaskId) -> bool
取消定时器
§参数
task_id: 任务 ID
§返回
如果任务存在且成功取消返回 true,否则返回 false
§示例
use kestrel_protocol_timer::{TimerWheel, TimerTask};
use std::time::Duration;
#[tokio::main]
async fn main() {
let timer = TimerWheel::with_defaults();
let task = TimerWheel::create_task(Duration::from_secs(10), || async {});
let task_id = task.get_id();
let _handle = timer.register(task);
// 使用任务 ID 取消
let cancelled = timer.cancel(task_id);
println!("取消成功: {}", cancelled);
}Sourcepub fn cancel_batch(&self, task_ids: &[TaskId]) -> usize
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), || async {});
let task2 = TimerWheel::create_task(Duration::from_secs(10), || async {});
let task3 = TimerWheel::create_task(Duration::from_secs(10), || async {});
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);
}Trait Implementations§
Auto Trait Implementations§
impl Freeze for TimerWheel
impl !RefUnwindSafe for TimerWheel
impl Send for TimerWheel
impl Sync for TimerWheel
impl Unpin for TimerWheel
impl !UnwindSafe for TimerWheel
Blanket Implementations§
Source§impl<T> BorrowMut<T> for Twhere
T: ?Sized,
impl<T> BorrowMut<T> for Twhere
T: ?Sized,
Source§fn borrow_mut(&mut self) -> &mut T
fn borrow_mut(&mut self) -> &mut T
Mutably borrows from an owned value. Read more