pub struct TimerWheel { /* private fields */ }Expand description
时间轮定时器管理器
Implementations§
Source§impl TimerWheel
impl TimerWheel
Sourcepub fn new(
tick_duration: Duration,
slot_count: usize,
) -> Result<Self, TimerError>
pub fn new( tick_duration: Duration, slot_count: usize, ) -> Result<Self, TimerError>
创建新的定时器管理器
§参数
tick_duration: 每个 tick 的时间长度(建议 10ms)slot_count: 槽位数量(必须是 2 的幂次方,建议 512 或 1024)
§返回
Ok(Self): 成功创建定时器管理器Err(TimerError): 槽位数量无效
§示例
use timer::TimerWheel;
use std::time::Duration;
#[tokio::main]
async fn main() {
let timer = TimerWheel::new(Duration::from_millis(10), 512).unwrap();
}Sourcepub fn with_defaults() -> Result<Self, TimerError>
pub fn with_defaults() -> Result<Self, TimerError>
创建带默认配置的定时器管理器
- tick 时长: 10ms
- 槽位数量: 512
§返回
Ok(Self): 成功创建定时器管理器Err(TimerError): 创建失败(不太可能,因为使用的是有效的默认值)
Sourcepub fn create_service(&self) -> TimerService
pub fn create_service(&self) -> TimerService
创建与此时间轮绑定的 TimerService
§返回
绑定到此时间轮的 TimerService 实例
§示例
use timer::TimerWheel;
use std::time::Duration;
#[tokio::main]
async fn main() {
let timer = TimerWheel::with_defaults().unwrap();
let mut service = timer.create_service();
// 直接通过 service 批量调度定时器
let callbacks: Vec<_> = (0..5)
.map(|_| (Duration::from_millis(100), || async {}))
.collect();
service.schedule_once_batch(callbacks).await.unwrap();
// 接收超时通知
let mut rx = service.take_receiver().unwrap();
while let Some(task_id) = rx.recv().await {
println!("Task {:?} completed", task_id);
}
}Sourcepub async fn schedule_once<C>(
&self,
delay: Duration,
callback: C,
) -> Result<TimerHandle, TimerError>where
C: TimerCallback,
pub async fn schedule_once<C>(
&self,
delay: Duration,
callback: C,
) -> Result<TimerHandle, TimerError>where
C: TimerCallback,
调度一次性定时器
§参数
delay: 延迟时间callback: 实现了 TimerCallback trait 的回调对象
§返回
Ok(TimerHandle): 成功调度,返回定时器句柄,可用于取消定时器Err(TimerError): 内部错误
§示例
use timer::TimerWheel;
use std::time::Duration;
use std::sync::Arc;
#[tokio::main]
async fn main() {
let timer = TimerWheel::with_defaults().unwrap();
let handle = timer.schedule_once(Duration::from_secs(1), || async {
println!("Timer fired!");
}).await.unwrap();
tokio::time::sleep(Duration::from_secs(2)).await;
}Sourcepub async fn schedule_once_batch<C>(
&self,
callbacks: Vec<(Duration, C)>,
) -> Result<BatchHandle, TimerError>where
C: TimerCallback,
pub async fn schedule_once_batch<C>(
&self,
callbacks: Vec<(Duration, C)>,
) -> Result<BatchHandle, TimerError>where
C: TimerCallback,
批量调度一次性定时器
§参数
tasks: (延迟时间, 回调) 的元组列表
§返回
Ok(BatchHandle): 成功调度,返回批量定时器句柄Err(TimerError): 内部错误
§性能优势
- 批量处理减少锁竞争
- 内部优化批量插入操作
- 共享 Wheel 引用减少内存开销
§示例
use timer::TimerWheel;
use std::time::Duration;
use std::sync::Arc;
use std::sync::atomic::{AtomicU32, Ordering};
#[tokio::main]
async fn main() {
let timer = TimerWheel::with_defaults().unwrap();
let counter = Arc::new(AtomicU32::new(0));
// 动态生成批量回调
let callbacks: Vec<(Duration, _)> = (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 batch = timer.schedule_once_batch(callbacks).await.unwrap();
println!("Scheduled {} timers", batch.len());
// 批量取消所有定时器
let cancelled = batch.cancel_all();
println!("Cancelled {} timers", cancelled);
}Sourcepub async fn schedule_once_notify(
&self,
delay: Duration,
) -> Result<TimerHandle, TimerError>
pub async fn schedule_once_notify( &self, delay: Duration, ) -> Result<TimerHandle, TimerError>
调度一次性通知定时器(无回调,仅通知)
§参数
delay: 延迟时间
§返回
Ok(TimerHandle): 成功调度,返回定时器句柄,可通过into_completion_receiver()获取通知接收器Err(TimerError): 内部错误
§示例
use timer::TimerWheel;
use std::time::Duration;
#[tokio::main]
async fn main() {
let timer = TimerWheel::with_defaults().unwrap();
let handle = timer.schedule_once_notify(Duration::from_secs(1)).await.unwrap();
// 获取完成通知接收器
handle.into_completion_receiver().0.await.ok();
println!("Timer completed!");
}Sourcepub fn cancel_batch(&self, task_ids: &[TaskId]) -> usize
pub fn cancel_batch(&self, task_ids: &[TaskId]) -> usize
批量取消定时器
§参数
task_ids: 要取消的任务 ID 列表
§返回
成功取消的任务数量
§性能优势
- 批量处理减少锁竞争
- 内部优化批量取消操作
§示例
use timer::TimerWheel;
use std::time::Duration;
#[tokio::main]
async fn main() {
let timer = TimerWheel::with_defaults().unwrap();
// 创建多个定时器
let handle1 = timer.schedule_once(Duration::from_secs(10), || async {}).await.unwrap();
let handle2 = timer.schedule_once(Duration::from_secs(10), || async {}).await.unwrap();
let handle3 = timer.schedule_once(Duration::from_secs(10), || async {}).await.unwrap();
// 批量取消
let task_ids = vec![handle1.task_id(), handle2.task_id(), handle3.task_id()];
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