TimerService

Struct TimerService 

Source
pub struct TimerService { /* private fields */ }
Expand description

TimerService - 基于 Actor 模式的定时器服务

管理多个定时器句柄,监听所有超时事件,并将 TaskId 聚合转发给用户。

§特性

  • 自动监听所有添加的定时器句柄的超时事件
  • 超时后自动从内部管理中移除该任务
  • 将超时的 TaskId 转发到统一的通道供用户接收
  • 支持动态添加 BatchHandle 和 TimerHandle

§示例

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 callbacks: Vec<_> = (0..5)
        .map(|_| (Duration::from_millis(100), || async {}))
        .collect();
    let tasks = TimerService::create_batch(callbacks);
    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);
    }
}

Implementations§

Source§

impl TimerService

Source

pub fn take_receiver(&mut self) -> Option<Receiver<TaskId>>

获取超时接收器(转移所有权)

§返回

超时通知接收器,如果已经被取走则返回 None

§注意

此方法只能调用一次,因为它会转移接收器的所有权

§示例
let timer = TimerWheel::with_defaults();
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);
}
Source

pub async fn cancel_task(&self, task_id: TaskId) -> bool

取消指定的任务

§参数
  • task_id: 要取消的任务 ID
§返回
  • Ok(true): 任务存在且成功取消
  • Ok(false): 任务不存在或取消失败
  • Err(String): 发送命令失败
§性能说明

此方法使用直接取消优化,不需要等待 Actor 处理,大幅降低延迟

§示例
let timer = TimerWheel::with_defaults();
let service = timer.create_service();
 
// 使用两步式 API 调度定时器
let task = TimerService::create_task(Duration::from_secs(10), || async {});
let task_id = task.get_id();
service.register(task).await;
 
// 取消任务
let cancelled = service.cancel_task(task_id).await;
println!("Task cancelled: {}", cancelled);
Source

pub async fn cancel_batch(&self, task_ids: &[TaskId]) -> usize

批量取消任务

使用底层的批量取消操作一次性取消多个任务,性能优于循环调用 cancel_task。

§参数
  • task_ids: 要取消的任务 ID 列表
§返回

成功取消的任务数量

§示例
let timer = TimerWheel::with_defaults();
let service = timer.create_service();
 
let callbacks: Vec<_> = (0..10)
    .map(|_| (Duration::from_secs(10), || async {}))
    .collect();
let tasks = TimerService::create_batch(callbacks);
let task_ids: Vec<_> = tasks.iter().map(|t| t.get_id()).collect();
service.register_batch(tasks).await;
 
// 批量取消
let cancelled = service.cancel_batch(&task_ids).await;
println!("成功取消 {} 个任务", cancelled);
Source

pub fn create_task<C>(delay: Duration, callback: C) -> TimerTask
where C: TimerCallback,

创建定时器任务(静态方法,申请阶段)

§参数
  • delay: 延迟时间
  • callback: 实现了 TimerCallback trait 的回调对象
§返回

返回 TimerTask,需要通过 register() 注册

§示例
let timer = TimerWheel::with_defaults();
let service = timer.create_service();
 
// 步骤 1: 创建任务
let task = TimerService::create_task(Duration::from_millis(100), || async {
    println!("Timer fired!");
});
 
let task_id = task.get_id();
println!("Created task: {:?}", task_id);
 
// 步骤 2: 注册任务
service.register(task).await;
Source

pub fn create_batch<C>(callbacks: Vec<(Duration, C)>) -> Vec<TimerTask>
where C: TimerCallback,

批量创建定时器任务(静态方法,申请阶段)

§参数
  • callbacks: (延迟时间, 回调) 的元组列表
§返回

返回 TimerTask 列表,需要通过 register_batch() 注册

§示例
let timer = TimerWheel::with_defaults();
let service = timer.create_service();
 
// 步骤 1: 批量创建任务
let callbacks: Vec<_> = (0..3)
    .map(|i| (Duration::from_millis(100 * (i + 1)), move || async move {
        println!("Timer {} fired!", i);
    }))
    .collect();
 
let tasks = TimerService::create_batch(callbacks);
println!("Created {} tasks", tasks.len());
 
// 步骤 2: 批量注册任务
service.register_batch(tasks).await;
Source

pub async fn register(&self, task: TimerTask)

注册定时器任务到服务(注册阶段)

§参数
  • task: 通过 create_task() 创建的任务
§示例
let timer = TimerWheel::with_defaults();
let service = timer.create_service();
 
let task = TimerService::create_task(Duration::from_millis(100), || async {
    println!("Timer fired!");
});
let task_id = task.get_id();
 
service.register(task).await;
Source

pub async fn register_batch(&self, tasks: Vec<TimerTask>)

批量注册定时器任务到服务(注册阶段)

§参数
  • tasks: 通过 create_batch() 创建的任务列表
§示例
let timer = TimerWheel::with_defaults();
let service = timer.create_service();
 
let callbacks: Vec<_> = (0..3)
    .map(|_| (Duration::from_secs(1), || async {}))
    .collect();
let tasks = TimerService::create_batch(callbacks);
 
service.register_batch(tasks).await;
Source

pub async fn shutdown(self)

优雅关闭 TimerService

§示例
let timer = TimerWheel::with_defaults();
let mut service = timer.create_service();
 
// 使用 service...
 
service.shutdown().await;

Trait Implementations§

Source§

impl Drop for TimerService

Source§

fn drop(&mut self)

Executes the destructor for this type. Read more

Auto Trait Implementations§

Blanket Implementations§

Source§

impl<T> Any for T
where T: 'static + ?Sized,

Source§

fn type_id(&self) -> TypeId

Gets the TypeId of self. Read more
Source§

impl<T> Borrow<T> for T
where T: ?Sized,

Source§

fn borrow(&self) -> &T

Immutably borrows from an owned value. Read more
Source§

impl<T> BorrowMut<T> for T
where T: ?Sized,

Source§

fn borrow_mut(&mut self) -> &mut T

Mutably borrows from an owned value. Read more
Source§

impl<T> From<T> for T

Source§

fn from(t: T) -> T

Returns the argument unchanged.

Source§

impl<T, U> Into<U> for T
where U: From<T>,

Source§

fn into(self) -> U

Calls U::from(self).

That is, this conversion is whatever the implementation of From<T> for U chooses to do.

Source§

impl<T, U> TryFrom<U> for T
where U: Into<T>,

Source§

type Error = Infallible

The type returned in the event of a conversion error.
Source§

fn try_from(value: U) -> Result<T, <T as TryFrom<U>>::Error>

Performs the conversion.
Source§

impl<T, U> TryInto<U> for T
where U: TryFrom<T>,

Source§

type Error = <U as TryFrom<T>>::Error

The type returned in the event of a conversion error.
Source§

fn try_into(self) -> Result<U, <U as TryFrom<T>>::Error>

Performs the conversion.