pub struct TimerService { /* private fields */ }Expand description
TimerService - 基于 Actor 模式的定时器服务
管理多个定时器句柄,监听所有超时事件,并将 TaskId 聚合转发给用户。
§特性
- 自动监听所有添加的定时器句柄的超时事件
- 超时后自动从内部管理中移除该任务
- 将超时的 TaskId 转发到统一的通道供用户接收
- 支持动态添加 BatchHandle 和 TimerHandle
§示例
use timer::{TimerWheel, TimerService};
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);
}
}Implementations§
Source§impl TimerService
impl TimerService
Sourcepub fn take_receiver(&mut self) -> Option<Receiver<TaskId>>
pub fn take_receiver(&mut self) -> Option<Receiver<TaskId>>
获取超时接收器(转移所有权)
§返回
超时通知接收器,如果已经被取走则返回 None
§注意
此方法只能调用一次,因为它会转移接收器的所有权
§示例
let timer = TimerWheel::with_defaults().unwrap();
let mut service = timer.create_service();
let mut rx = service.take_receiver().unwrap();
while let Some(task_id) = rx.recv().await {
println!("Task {:?} timed out", task_id);
}Sourcepub async fn cancel_task(&self, task_id: TaskId) -> Result<bool, String>
pub async fn cancel_task(&self, task_id: TaskId) -> Result<bool, String>
取消指定的任务
§参数
task_id: 要取消的任务 ID
§返回
Ok(true): 任务存在且成功取消Ok(false): 任务不存在或取消失败Err(String): 发送命令失败
§性能说明
此方法使用直接取消优化,不需要等待 Actor 处理,大幅降低延迟
§示例
let timer = TimerWheel::with_defaults().unwrap();
let service = timer.create_service();
// 直接通过 service 调度定时器
let task_id = service.schedule_once(Duration::from_secs(10), || async {}).await.unwrap();
// 取消任务
let cancelled = service.cancel_task(task_id).await.unwrap();
println!("Task cancelled: {}", cancelled);Sourcepub async fn cancel_batch(&self, task_ids: &[TaskId]) -> usize
pub async fn cancel_batch(&self, task_ids: &[TaskId]) -> usize
批量取消任务
使用底层的批量取消操作一次性取消多个任务,性能优于循环调用 cancel_task。
§参数
task_ids: 要取消的任务 ID 列表
§返回
成功取消的任务数量
§示例
let timer = TimerWheel::with_defaults().unwrap();
let service = timer.create_service();
let callbacks: Vec<_> = (0..10)
.map(|_| (Duration::from_secs(10), || async {}))
.collect();
let task_ids = service.schedule_once_batch(callbacks).await.unwrap();
// 批量取消
let cancelled = service.cancel_batch(&task_ids).await;
println!("成功取消 {} 个任务", cancelled);Sourcepub async fn schedule_once<C>(
&self,
delay: Duration,
callback: C,
) -> Result<TaskId, TimerError>where
C: TimerCallback,
pub async fn schedule_once<C>(
&self,
delay: Duration,
callback: C,
) -> Result<TaskId, TimerError>where
C: TimerCallback,
调度一次性定时器
创建定时器并自动添加到服务管理中,无需手动调用 add_timer_handle
§参数
delay: 延迟时间callback: 实现了 TimerCallback trait 的回调对象
§返回
Ok(TaskId): 成功调度,返回任务IDErr(TimerError): 调度失败
§示例
let timer = TimerWheel::with_defaults().unwrap();
let mut service = timer.create_service();
let task_id = service.schedule_once(Duration::from_millis(100), || async {
println!("Timer fired!");
}).await.unwrap();
println!("Scheduled task: {:?}", task_id);Sourcepub async fn schedule_once_batch<C>(
&self,
callbacks: Vec<(Duration, C)>,
) -> Result<Vec<TaskId>, TimerError>where
C: TimerCallback,
pub async fn schedule_once_batch<C>(
&self,
callbacks: Vec<(Duration, C)>,
) -> Result<Vec<TaskId>, TimerError>where
C: TimerCallback,
批量调度一次性定时器
批量创建定时器并自动添加到服务管理中
§参数
callbacks: (延迟时间, 回调) 的元组列表
§返回
Ok(Vec<TaskId>): 成功调度,返回所有任务IDErr(TimerError): 调度失败
§示例
let timer = TimerWheel::with_defaults().unwrap();
let mut service = timer.create_service();
let callbacks: Vec<_> = (0..3)
.map(|i| (Duration::from_millis(100 * (i + 1)), move || async move {
println!("Timer {} fired!", i);
}))
.collect();
let task_ids = service.schedule_once_batch(callbacks).await.unwrap();
println!("Scheduled {} tasks", task_ids.len());Sourcepub async fn schedule_once_notify(
&self,
delay: Duration,
) -> Result<TaskId, TimerError>
pub async fn schedule_once_notify( &self, delay: Duration, ) -> Result<TaskId, TimerError>
调度一次性通知定时器(无回调,仅通知)
创建仅通知的定时器并自动添加到服务管理中
§参数
delay: 延迟时间
§返回
Ok(TaskId): 成功调度,返回任务IDErr(TimerError): 调度失败
§示例
let timer = TimerWheel::with_defaults().unwrap();
let mut service = timer.create_service();
let task_id = service.schedule_once_notify(Duration::from_millis(100)).await.unwrap();
println!("Scheduled notify task: {:?}", task_id);
// 可以通过 timeout_receiver 接收超时通知Trait Implementations§
Auto Trait Implementations§
impl Freeze for TimerService
impl !RefUnwindSafe for TimerService
impl Send for TimerService
impl Sync for TimerService
impl Unpin for TimerService
impl !UnwindSafe for TimerService
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