pub struct TimerWheel { /* private fields */ }Expand description
时间轮定时器管理器
Implementations§
Source§impl TimerWheel
impl TimerWheel
Sourcepub fn new(config: WheelConfig, batch_config: BatchConfig) -> Self
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);
}Sourcepub fn with_defaults() -> Self
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();
}Sourcepub fn create_service(&self, service_config: ServiceConfig) -> TimerService
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);
}
}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(
delay: Duration,
callback: Option<CallbackWrapper>,
) -> TimerTask
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);
}Sourcepub fn create_batch(delays: Vec<Duration>) -> Vec<TimerTask>
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);
}Sourcepub fn create_batch_with_callbacks(
callbacks: Vec<(Duration, Option<CallbackWrapper>)>,
) -> Vec<TimerTask>
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);
}Sourcepub fn register(&self, task: TimerTask) -> TimerHandle
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();
}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 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());
}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, 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);
}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), 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);
}Sourcepub fn postpone(
&self,
task_id: TaskId,
new_delay: Duration,
callback: Option<CallbackWrapper>,
) -> bool
pub fn postpone( &self, task_id: TaskId, new_delay: Duration, callback: Option<CallbackWrapper>, ) -> bool
推迟定时器
§参数
task_id: 要推迟的任务 IDnew_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);
}Sourcepub fn postpone_batch(&self, updates: Vec<(TaskId, Duration)>) -> usize
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);
}Sourcepub fn postpone_batch_with_callbacks(
&self,
updates: Vec<(TaskId, Duration, Option<CallbackWrapper>)>,
) -> usize
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);
}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