Skip to main content

kestrel_timer/timer/
handle.rs

1use crate::error::TimerError;
2use crate::task::{CompletionReceiver, TaskId};
3use crate::wheel::Wheel;
4use parking_lot::Mutex;
5use std::sync::Arc;
6
7/// Timer handle for managing timer lifecycle (without completion receiver)
8///
9/// Note: This type does not implement Clone to prevent duplicate cancellation of the same timer. Each timer should have only one owner.
10///
11/// 定时器句柄,用于管理定时器生命周期(不含完成通知接收器)
12///
13/// 注意:此类型未实现 Clone 以防止重复取消同一定时器。每个定时器应该只有一个所有者。
14pub struct TimerHandle {
15    pub(crate) task_id: TaskId,
16    pub(crate) wheel: Arc<Mutex<Wheel>>,
17}
18
19impl TimerHandle {
20    #[inline]
21    pub(crate) fn new(task_id: TaskId, wheel: Arc<Mutex<Wheel>>) -> Self {
22        Self { task_id, wheel }
23    }
24
25    /// Cancel the timer
26    ///
27    /// # Returns
28    /// Returns true if task exists and is successfully cancelled, otherwise false
29    ///
30    /// 取消定时器
31    ///
32    /// # 返回值
33    /// 如果任务存在且成功取消则返回 true,否则返回 false
34    ///
35    /// # Examples (示例)
36    /// ```no_run
37    /// # use kestrel_timer::{TimerWheel, CallbackWrapper, TimerTask};
38    /// # use std::time::Duration;
39    /// #
40    /// # #[tokio::main]
41    /// # async fn main() {
42    /// let timer = TimerWheel::with_defaults();
43    /// let callback = Some(CallbackWrapper::new(|| async {}));
44    /// let task = TimerTask::new_oneshot(Duration::from_secs(1), callback);
45    /// let allocated_handle = timer.allocate_handle();
46    /// let handle = timer.register(allocated_handle, task).unwrap();
47    ///
48    /// // Cancel the timer
49    /// let success = handle.cancel().unwrap();
50    /// println!("Canceled successfully: {}", success);
51    /// # }
52    /// ```
53    #[inline]
54    pub fn cancel(&self) -> Result<bool, TimerError> {
55        let mut wheel = self.wheel.lock();
56        wheel.cancel(self.task_id)
57    }
58
59    /// Postpone the timer
60    ///
61    /// # Parameters
62    /// - `new_delay`: New delay duration, recalculated from current time
63    /// - `callback`: New callback function, pass `None` to keep original callback, pass `Some` to replace with new callback
64    ///
65    /// # Returns
66    /// Returns true if task exists and is successfully postponed, otherwise false
67    ///
68    /// 推迟定时器
69    ///
70    /// # 参数
71    /// - `new_delay`: 新的延迟时间,从当前时间重新计算
72    /// - `callback`: 新的回调函数,传递 `None` 保持原始回调,传递 `Some` 替换为新的回调
73    ///
74    /// # 返回值
75    /// 如果任务存在且成功推迟则返回 true,否则返回 false
76    ///
77    /// # Examples (示例)
78    /// ```no_run
79    /// # use kestrel_timer::{TimerWheel, CallbackWrapper, TimerTask};
80    /// # use std::time::Duration;
81    /// #
82    /// # #[tokio::main]
83    /// # async fn main() {
84    /// let timer = TimerWheel::with_defaults();
85    /// let callback = Some(CallbackWrapper::new(|| async {}));
86    /// let task = TimerTask::new_oneshot(Duration::from_secs(1), callback);
87    /// let allocated_handle = timer.allocate_handle();
88    /// let handle = timer.register(allocated_handle, task).unwrap();
89    ///
90    /// // Postpone to 5 seconds
91    /// let success = handle.postpone(Duration::from_secs(5), None).unwrap();
92    /// println!("Postponed successfully: {}", success);
93    /// # }
94    /// ```
95    #[inline]
96    pub fn postpone(
97        &self,
98        new_delay: std::time::Duration,
99        callback: Option<crate::task::CallbackWrapper>,
100    ) -> Result<bool, TimerError> {
101        let mut wheel = self.wheel.lock();
102        wheel.postpone_at(self.task_id, new_delay, callback)
103    }
104}
105
106/// Timer handle with completion receiver for managing timer lifecycle
107///
108/// Note: This type does not implement Clone to prevent duplicate cancellation of the same timer. Each timer should have only one owner.
109///
110/// 包含完成通知接收器的定时器句柄,用于管理定时器生命周期
111///
112/// 注意:此类型未实现 Clone 以防止重复取消同一定时器。每个定时器应该只有一个所有者。
113pub struct TimerHandleWithCompletion {
114    handle: TimerHandle,
115    pub(crate) completion_rx: CompletionReceiver,
116}
117
118impl TimerHandleWithCompletion {
119    pub(crate) fn new(handle: TimerHandle, completion_rx: CompletionReceiver) -> Self {
120        Self {
121            handle,
122            completion_rx,
123        }
124    }
125
126    /// Cancel the timer
127    ///
128    /// # Returns
129    /// Returns true if task exists and is successfully cancelled, otherwise false
130    ///
131    /// 取消定时器
132    ///
133    /// # 返回值
134    /// 如果任务存在且成功取消则返回 true,否则返回 false
135    ///
136    /// # Examples (示例)
137    /// ```no_run
138    /// # use kestrel_timer::{TimerWheel, CallbackWrapper, TimerTask};
139    /// # use std::time::Duration;
140    /// #
141    /// # #[tokio::main]
142    /// # async fn main() {
143    /// let timer = TimerWheel::with_defaults();
144    /// let callback = Some(CallbackWrapper::new(|| async {}));
145    /// let task = TimerTask::new_oneshot(Duration::from_secs(1), callback);
146    /// let allocated_handle = timer.allocate_handle();
147    /// let handle = timer.register(allocated_handle, task).unwrap();
148    ///
149    /// // Cancel the timer
150    /// let success = handle.cancel().unwrap();
151    /// println!("Canceled successfully: {}", success);
152    /// # }
153    /// ```
154    pub fn cancel(&self) -> Result<bool, TimerError> {
155        self.handle.cancel()
156    }
157
158    /// Postpone the timer
159    ///
160    /// # Parameters
161    /// - `new_delay`: New delay duration, recalculated from current time
162    /// - `callback`: New callback function, pass `None` to keep original callback, pass `Some` to replace with new callback
163    ///
164    /// # Returns
165    /// Returns true if task exists and is successfully postponed, otherwise false
166    ///
167    /// 推迟定时器
168    ///
169    /// # 参数
170    /// - `new_delay`: 新的延迟时间,从当前时间重新计算
171    /// - `callback`: 新的回调函数,传递 `None` 保持原始回调,传递 `Some` 替换为新的回调
172    ///
173    /// # 返回值
174    /// 如果任务存在且成功推迟则返回 true,否则返回 false
175    ///
176    /// # Examples (示例)
177    /// ```no_run
178    /// # use kestrel_timer::{TimerWheel, CallbackWrapper, TimerTask};
179    /// # use std::time::Duration;
180    /// #
181    /// # #[tokio::main]
182    /// # async fn main() {
183    /// let timer = TimerWheel::with_defaults();
184    /// let callback = Some(CallbackWrapper::new(|| async {}));
185    /// let task = TimerTask::new_oneshot(Duration::from_secs(1), callback);
186    /// let allocated_handle = timer.allocate_handle();
187    /// let handle = timer.register(allocated_handle, task).unwrap();
188    ///
189    /// // Postpone to 5 seconds
190    /// let success = handle.postpone(Duration::from_secs(5), None).unwrap();
191    /// println!("Postponed successfully: {}", success);
192    /// # }
193    /// ```
194    pub fn postpone(
195        &self,
196        new_delay: std::time::Duration,
197        callback: Option<crate::task::CallbackWrapper>,
198    ) -> Result<bool, TimerError> {
199        self.handle.postpone(new_delay, callback)
200    }
201
202    /// Split handle into completion receiver and timer handle
203    ///
204    /// 将句柄拆分为完成通知接收器和定时器句柄
205    ///
206    /// # Examples (示例)
207    /// ```no_run
208    /// # use kestrel_timer::{TimerWheel, CallbackWrapper, TimerTask};
209    /// # use std::time::Duration;
210    /// #
211    /// # #[tokio::main]
212    /// # async fn main() {
213    /// let timer = TimerWheel::with_defaults();
214    /// let callback = Some(CallbackWrapper::new(|| async {
215    ///     println!("Timer fired!");
216    /// }));
217    /// let task = TimerTask::new_oneshot(Duration::from_secs(1), callback);
218    /// let allocated_handle = timer.allocate_handle();
219    /// let handle = timer.register(allocated_handle, task).unwrap();
220    ///
221    /// // Split into receiver and handle
222    /// // 拆分为接收器和句柄
223    /// let (rx, handle) = handle.into_parts();
224    ///
225    /// // Wait for timer completion
226    /// // 等待定时器完成
227    /// use kestrel_timer::CompletionReceiver;
228    /// match rx {
229    ///     CompletionReceiver::OneShot(receiver) => {
230    ///         receiver.recv().await.unwrap();
231    ///     },
232    ///     _ => {}
233    /// }
234    /// println!("Timer completed!");
235    /// # }
236    /// ```
237    pub fn into_parts(self) -> (CompletionReceiver, TimerHandle) {
238        (self.completion_rx, self.handle)
239    }
240}
241
242/// Batch timer handle for managing batch-scheduled timers (without completion receivers)
243///
244/// Note: This type does not implement Clone to prevent duplicate cancellation of the same batch of timers. Use `into_iter()` or `into_handles()` to access individual timer handles.
245///
246/// 批量定时器句柄,用于管理批量调度的定时器(不含完成通知接收器)
247///
248/// 注意:此类型未实现 Clone 以防止重复取消同一批定时器。使用 `into_iter()` 或 `into_handles()` 访问单个定时器句柄。
249pub struct BatchHandle {
250    pub(crate) task_ids: Vec<TaskId>,
251    pub(crate) wheel: Arc<Mutex<Wheel>>,
252}
253
254impl BatchHandle {
255    #[inline]
256    pub(crate) fn new(task_ids: Vec<TaskId>, wheel: Arc<Mutex<Wheel>>) -> Self {
257        Self { task_ids, wheel }
258    }
259
260    /// Cancel all timers in batch
261    ///
262    /// # Returns
263    /// Number of successfully cancelled tasks
264    ///
265    /// 批量取消所有定时器
266    ///
267    /// # 返回值
268    /// 成功取消的任务数量
269    ///
270    /// # Examples (示例)
271    /// ```no_run
272    /// # use kestrel_timer::{TimerWheel, CallbackWrapper, TimerTask};
273    /// # use std::time::Duration;
274    /// #
275    /// # #[tokio::main]
276    /// # async fn main() {
277    /// let timer = TimerWheel::with_defaults();
278    /// let handles = timer.allocate_handles(10);
279    /// let tasks: Vec<_> = (0..10)
280    ///     .map(|_| TimerTask::new_oneshot(Duration::from_secs(1), None))
281    ///     .collect();
282    /// let batch = timer.register_batch(handles, tasks).unwrap();
283    ///
284    /// let cancelled = batch.cancel_all().unwrap();
285    /// println!("Canceled {} timers", cancelled);
286    /// # }
287    /// ```
288    #[inline]
289    pub fn cancel_all(self) -> Result<usize, TimerError> {
290        let mut wheel = self.wheel.lock();
291        wheel.cancel_batch(&self.task_ids)
292    }
293
294    /// Convert batch handle to Vec of individual timer handles
295    ///
296    /// Consumes BatchHandle and creates independent TimerHandle for each task
297    ///
298    /// 将批量句柄转换为单个定时器句柄的 Vec
299    ///
300    /// 消费 BatchHandle 并为每个任务创建独立的 TimerHandle
301    ///
302    /// # Examples (示例)
303    /// ```no_run
304    /// # use kestrel_timer::{TimerWheel, CallbackWrapper, TimerTask};
305    /// # use std::time::Duration;
306    /// #
307    /// # #[tokio::main]
308    /// # async fn main() {
309    /// let timer = TimerWheel::with_defaults();
310    /// let handles = timer.allocate_handles(3);
311    /// let tasks: Vec<_> = (0..3)
312    ///     .map(|_| TimerTask::new_oneshot(Duration::from_secs(1), None))
313    ///     .collect();
314    /// let batch = timer.register_batch(handles, tasks).unwrap();
315    ///
316    /// // Convert to individual handles
317    /// // 转换为单个句柄
318    /// let handles = batch.into_handles();
319    /// for handle in handles {
320    ///     // Can operate each handle individually
321    ///     // 可以单独操作每个句柄
322    /// }
323    /// # }
324    /// ```
325    #[inline]
326    pub fn into_handles(self) -> Vec<TimerHandle> {
327        self.task_ids
328            .into_iter()
329            .map(|task_id| TimerHandle::new(task_id, self.wheel.clone()))
330            .collect()
331    }
332
333    /// Get the number of batch tasks
334    ///
335    /// 获取批量任务数量
336    #[inline]
337    pub fn len(&self) -> usize {
338        self.task_ids.len()
339    }
340
341    /// Check if batch tasks are empty
342    ///
343    /// 检查批量任务是否为空
344    #[inline]
345    pub fn is_empty(&self) -> bool {
346        self.task_ids.is_empty()
347    }
348
349    /// Get reference to all task IDs
350    ///
351    /// 获取所有任务 ID 的引用
352    #[inline]
353    pub fn task_ids(&self) -> &[TaskId] {
354        &self.task_ids
355    }
356
357    /// Batch postpone timers (keep original callbacks)
358    ///
359    /// # Parameters
360    /// - `new_delay`: New delay duration applied to all timers
361    ///
362    /// # Returns
363    /// Number of successfully postponed tasks
364    ///
365    /// 批量推迟定时器 (保持原始回调)
366    ///
367    /// # 参数
368    /// - `new_delay`: 应用于所有定时器的新延迟时间
369    ///
370    /// # 返回值
371    /// 成功推迟的任务数量
372    ///
373    /// # Examples (示例)
374    /// ```no_run
375    /// # use kestrel_timer::{TimerWheel, CallbackWrapper};
376    /// # use std::time::Duration;
377    /// #
378    /// # #[tokio::main]
379    /// # async fn main() {
380    /// # use kestrel_timer::TimerTask;
381    /// let timer = TimerWheel::with_defaults();
382    /// let handles = timer.allocate_handles(10);
383    /// let tasks: Vec<_> = (0..10)
384    ///     .map(|_| TimerTask::new_oneshot(Duration::from_secs(1), None))
385    ///     .collect();
386    /// let batch_with_completion = timer.register_batch(handles, tasks).unwrap();
387    /// let (rxs, batch) = batch_with_completion.into_parts();
388    ///
389    /// // Postpone all timers to 5 seconds
390    /// let postponed = batch.postpone_all(Duration::from_secs(5)).unwrap();
391    /// println!("Postponed {} timers", postponed);
392    /// # }
393    /// ```
394    #[inline]
395    pub fn postpone_all(self, new_delay: std::time::Duration) -> Result<usize, TimerError> {
396        let updates: Vec<_> = self.task_ids.iter().map(|&id| (id, new_delay)).collect();
397        let mut wheel = self.wheel.lock();
398        wheel.postpone_batch_at(updates)
399    }
400
401    /// Batch postpone timers with individual delays (keep original callbacks)
402    ///
403    /// # Parameters
404    /// - `delays`: List of new delay durations for each timer (must match the number of tasks)
405    ///
406    /// # Returns
407    /// Number of successfully postponed tasks
408    ///
409    /// 批量推迟定时器,每个定时器使用不同延迟 (保持原始回调)
410    ///
411    /// # 参数
412    /// - `delays`: 每个定时器的新延迟时间列表(必须与任务数量匹配)
413    ///
414    /// # 返回值
415    /// 成功推迟的任务数量
416    ///
417    /// # Examples (示例)
418    /// ```no_run
419    /// # use kestrel_timer::{TimerWheel, CallbackWrapper, TimerTask};
420    /// # use std::time::Duration;
421    /// #
422    /// # #[tokio::main]
423    /// # async fn main() {
424    /// let timer = TimerWheel::with_defaults();
425    /// let handles = timer.allocate_handles(3);
426    /// let tasks: Vec<_> = (0..3)
427    ///     .map(|_| TimerTask::new_oneshot(Duration::from_secs(1), None))
428    ///     .collect();
429    /// let batch_with_completion = timer.register_batch(handles, tasks).unwrap();
430    /// let (rxs, mut batch) = batch_with_completion.into_parts();
431    ///
432    /// // Postpone each timer with different delays
433    /// let new_delays = vec![
434    ///     Duration::from_secs(2),
435    ///     Duration::from_secs(3),
436    ///     Duration::from_secs(4),
437    /// ];
438    /// let postponed = batch.postpone_each(new_delays).unwrap();
439    /// println!("Postponed {} timers", postponed);
440    /// # }
441    /// ```
442    #[inline]
443    pub fn postpone_each(&mut self, delays: Vec<std::time::Duration>) -> Result<usize, TimerError> {
444        if self.task_ids.len() != delays.len() {
445            return Err(TimerError::BatchLengthMismatch {
446                handles_len: self.task_ids.len(),
447                tasks_len: delays.len(),
448            });
449        }
450
451        let updates: Vec<_> = self.task_ids.iter().copied().zip(delays).collect();
452        let mut wheel = self.wheel.lock();
453        wheel.postpone_batch_at(updates)
454    }
455
456    /// Batch postpone timers with individual delays and callbacks
457    ///
458    /// # Parameters
459    /// - `updates`: List of tuples of (new delay, new callback) for each timer
460    ///
461    /// # Returns
462    /// Number of successfully postponed tasks
463    ///
464    /// 批量推迟定时器,每个定时器使用不同延迟和回调
465    ///
466    /// # 参数
467    /// - `updates`: 每个定时器的 (新延迟, 新回调) 元组列表
468    ///
469    /// # 返回值
470    /// 成功推迟的任务数量
471    ///
472    /// # Examples (示例)
473    /// ```no_run
474    /// # use kestrel_timer::{TimerWheel, CallbackWrapper, TimerTask};
475    /// # use std::time::Duration;
476    /// #
477    /// # #[tokio::main]
478    /// # async fn main() {
479    /// let timer = TimerWheel::with_defaults();
480    /// let handles = timer.allocate_handles(3);
481    /// let tasks: Vec<_> = (0..3)
482    ///     .map(|_| TimerTask::new_oneshot(Duration::from_secs(1), None))
483    ///     .collect();
484    /// let batch_with_completion = timer.register_batch(handles, tasks).unwrap();
485    /// let (rxs, mut batch) = batch_with_completion.into_parts();
486    ///
487    /// // Postpone each timer with different delays and callbacks
488    /// let updates = vec![
489    ///     (Duration::from_secs(2), Some(CallbackWrapper::new(|| async {}))),
490    ///     (Duration::from_secs(3), None),
491    ///     (Duration::from_secs(4), Some(CallbackWrapper::new(|| async {}))),
492    /// ];
493    /// let postponed = batch.postpone_each_with_callbacks(updates).unwrap();
494    /// println!("Postponed {} timers", postponed);
495    /// # }
496    /// ```
497    #[inline]
498    pub fn postpone_each_with_callbacks(
499        &mut self,
500        updates: Vec<(std::time::Duration, Option<crate::task::CallbackWrapper>)>,
501    ) -> Result<usize, TimerError> {
502        if self.task_ids.len() != updates.len() {
503            return Err(TimerError::BatchLengthMismatch {
504                handles_len: self.task_ids.len(),
505                tasks_len: updates.len(),
506            });
507        }
508
509        let updates_with_ids: Vec<_> = self
510            .task_ids
511            .iter()
512            .copied()
513            .zip(updates)
514            .map(|(id, (delay, callback))| (id, delay, callback))
515            .collect();
516        let mut wheel = self.wheel.lock();
517        wheel.postpone_batch_with_callbacks_at(updates_with_ids)
518    }
519}
520
521/// Batch timer handle with completion receivers for managing batch-scheduled timers
522///
523/// Note: This type does not implement Clone to prevent duplicate cancellation of the same batch of timers. Use `into_iter()` or `into_handles()` to access individual timer handles.
524///
525/// 包含完成通知接收器的批量定时器句柄,用于管理批量调度的定时器
526///
527/// 注意:此类型未实现 Clone 以防止重复取消同一批定时器。使用 `into_iter()` 或 `into_handles()` 访问单个定时器句柄。
528pub struct BatchHandleWithCompletion {
529    handles: BatchHandle,
530    completion_rxs: Vec<CompletionReceiver>,
531}
532
533impl BatchHandleWithCompletion {
534    #[inline]
535    pub(crate) fn new(handles: BatchHandle, completion_rxs: Vec<CompletionReceiver>) -> Self {
536        Self {
537            handles,
538            completion_rxs,
539        }
540    }
541
542    /// Cancel all timers in batch
543    ///
544    /// # Returns
545    /// Number of successfully cancelled tasks
546    ///
547    /// 批量取消所有定时器
548    ///
549    /// # 返回值
550    /// 成功取消的任务数量
551    ///
552    /// # Examples (示例)
553    /// ```no_run
554    /// # use kestrel_timer::{TimerWheel, CallbackWrapper, TimerTask};
555    /// # use std::time::Duration;
556    /// #
557    /// # #[tokio::main]
558    /// # async fn main() {
559    /// let timer = TimerWheel::with_defaults();
560    /// let handles = timer.allocate_handles(10);
561    /// let tasks: Vec<_> = (0..10)
562    ///     .map(|_| TimerTask::new_oneshot(Duration::from_secs(1), None))
563    ///     .collect();
564    /// let batch = timer.register_batch(handles, tasks).unwrap();
565    ///
566    /// let cancelled = batch.cancel_all().unwrap();
567    /// println!("Canceled {} timers", cancelled);
568    /// # }
569    /// ```
570    #[inline]
571    pub fn cancel_all(self) -> Result<usize, TimerError> {
572        self.handles.cancel_all()
573    }
574
575    /// Convert batch handle to Vec of individual timer handles with completion receivers
576    ///
577    /// Consumes BatchHandleWithCompletion and creates independent TimerHandleWithCompletion for each task
578    ///
579    /// 将批量句柄转换为单个定时器句柄的 Vec
580    ///
581    /// 消费 BatchHandleWithCompletion 并为每个任务创建独立的 TimerHandleWithCompletion
582    ///
583    /// # Examples (示例)
584    /// ```no_run
585    /// # use kestrel_timer::{TimerWheel, CallbackWrapper, TimerTask};
586    /// # use std::time::Duration;
587    /// #
588    /// # #[tokio::main]
589    /// # async fn main() {
590    /// let timer = TimerWheel::with_defaults();
591    /// let handles = timer.allocate_handles(3);
592    /// let tasks: Vec<_> = (0..3)
593    ///     .map(|_| TimerTask::new_oneshot(Duration::from_secs(1), None))
594    ///     .collect();
595    /// let batch = timer.register_batch(handles, tasks).unwrap();
596    ///
597    /// // Convert to individual handles
598    /// // 转换为单个句柄
599    /// let handles = batch.into_handles();
600    /// for handle in handles {
601    ///     // Can operate each handle individually
602    ///     // 可以单独操作每个句柄
603    /// }
604    /// # }
605    /// ```
606    #[inline]
607    pub fn into_handles(self) -> Vec<TimerHandleWithCompletion> {
608        self.handles
609            .into_handles()
610            .into_iter()
611            .zip(self.completion_rxs)
612            .map(|(handle, rx)| TimerHandleWithCompletion::new(handle, rx))
613            .collect()
614    }
615
616    /// Get the number of batch tasks
617    ///
618    /// 获取批量任务数量
619    #[inline]
620    pub fn len(&self) -> usize {
621        self.handles.len()
622    }
623
624    /// Check if batch tasks are empty
625    ///
626    /// 检查批量任务是否为空
627    #[inline]
628    pub fn is_empty(&self) -> bool {
629        self.handles.is_empty()
630    }
631
632    /// Get reference to all task IDs
633    ///
634    /// 获取所有任务 ID 的引用
635    #[inline]
636    pub fn task_ids(&self) -> &[TaskId] {
637        self.handles.task_ids()
638    }
639
640    /// Split batch handle into completion receivers and batch handle
641    ///
642    /// 将批量句柄拆分为完成通知接收器列表和批量句柄
643    ///
644    /// # Examples (示例)
645    /// ```no_run
646    /// # use kestrel_timer::{TimerWheel, CallbackWrapper, TimerTask};
647    /// # use std::time::Duration;
648    /// #
649    /// # #[tokio::main]
650    /// # async fn main() {
651    /// let timer = TimerWheel::with_defaults();
652    /// let handles = timer.allocate_handles(3);
653    /// let tasks: Vec<_> = (0..3)
654    ///     .map(|_| TimerTask::new_oneshot(Duration::from_secs(1), None))
655    ///     .collect();
656    /// let batch = timer.register_batch(handles, tasks).unwrap();
657    ///
658    /// // Split into receivers and handle
659    /// // 拆分为接收器和句柄
660    /// use kestrel_timer::CompletionReceiver;
661    /// let (receivers, batch_handle) = batch.into_parts();
662    /// for rx in receivers {
663    ///     tokio::spawn(async move {
664    ///         match rx {
665    ///             CompletionReceiver::OneShot(receiver) => {
666    ///                 receiver.recv().await.unwrap();
667    ///                 println!("A timer completed!");
668    ///             },
669    ///             _ => {}
670    ///         }
671    ///     });
672    /// }
673    /// # }
674    /// ```
675    #[inline]
676    pub fn into_parts(self) -> (Vec<CompletionReceiver>, BatchHandle) {
677        let handle = BatchHandle::new(self.handles.task_ids.clone(), self.handles.wheel);
678        (self.completion_rxs, handle)
679    }
680
681    /// Batch postpone timers (keep original callbacks)
682    ///
683    /// # Parameters
684    /// - `new_delay`: New delay duration applied to all timers
685    ///
686    /// # Returns
687    /// Number of successfully postponed tasks
688    ///
689    /// 批量推迟定时器 (保持原始回调)
690    ///
691    /// # 参数
692    /// - `new_delay`: 应用于所有定时器的新延迟时间
693    ///
694    /// # 返回值
695    /// 成功推迟的任务数量
696    ///
697    /// # Examples (示例)
698    /// ```no_run
699    /// # use kestrel_timer::{TimerWheel, CallbackWrapper, TimerTask};
700    /// # use std::time::Duration;
701    /// #
702    /// # #[tokio::main]
703    /// # async fn main() {
704    /// let timer = TimerWheel::with_defaults();
705    /// let handles = timer.allocate_handles(10);
706    /// let tasks: Vec<_> = (0..10)
707    ///     .map(|_| TimerTask::new_oneshot(Duration::from_secs(1), None))
708    ///     .collect();
709    /// let batch = timer.register_batch(handles, tasks).unwrap();
710    ///
711    /// // Postpone all timers to 5 seconds
712    /// let postponed = batch.postpone_all(Duration::from_secs(5)).unwrap();
713    /// println!("Postponed {} timers", postponed);
714    /// # }
715    /// ```
716    #[inline]
717    pub fn postpone_all(self, new_delay: std::time::Duration) -> Result<usize, TimerError> {
718        self.handles.postpone_all(new_delay)
719    }
720
721    /// Batch postpone timers with individual delays (keep original callbacks)
722    ///
723    /// # Parameters
724    /// - `delays`: List of new delay durations for each timer (must match the number of tasks)
725    ///
726    /// # Returns
727    /// Number of successfully postponed tasks
728    ///
729    /// 批量推迟定时器,每个定时器使用不同延迟 (保持原始回调)
730    ///
731    /// # 参数
732    /// - `delays`: 每个定时器的新延迟时间列表(必须与任务数量匹配)
733    ///
734    /// # 返回值
735    /// 成功推迟的任务数量
736    ///
737    /// # Examples (示例)
738    /// ```no_run
739    /// # use kestrel_timer::{TimerWheel, CallbackWrapper, TimerTask};
740    /// # use std::time::Duration;
741    /// #
742    /// # #[tokio::main]
743    /// # async fn main() {
744    /// let timer = TimerWheel::with_defaults();
745    /// let handles = timer.allocate_handles(3);
746    /// let tasks: Vec<_> = (0..3)
747    ///     .map(|_| TimerTask::new_oneshot(Duration::from_secs(1), None))
748    ///     .collect();
749    /// let mut batch = timer.register_batch(handles, tasks).unwrap();
750    ///
751    /// // Postpone each timer with different delays
752    /// let new_delays = vec![
753    ///     Duration::from_secs(2),
754    ///     Duration::from_secs(3),
755    ///     Duration::from_secs(4),
756    /// ];
757    /// let postponed = batch.postpone_each(new_delays).unwrap();
758    /// println!("Postponed {} timers", postponed);
759    /// # }
760    /// ```
761    #[inline]
762    pub fn postpone_each(&mut self, delays: Vec<std::time::Duration>) -> Result<usize, TimerError> {
763        self.handles.postpone_each(delays)
764    }
765
766    /// Batch postpone timers with individual delays and callbacks
767    ///
768    /// # Parameters
769    /// - `updates`: List of tuples of (new delay, new callback) for each timer
770    ///
771    /// # Returns
772    /// Number of successfully postponed tasks
773    ///
774    /// 批量推迟定时器,每个定时器使用不同延迟和回调
775    ///
776    /// # 参数
777    /// - `updates`: 每个定时器的 (新延迟, 新回调) 元组列表
778    ///
779    /// # 返回值
780    /// 成功推迟的任务数量
781    ///
782    /// # Examples (示例)
783    /// ```no_run
784    /// # use kestrel_timer::{TimerWheel, CallbackWrapper, TimerTask};
785    /// # use std::time::Duration;
786    /// #
787    /// # #[tokio::main]
788    /// # async fn main() {
789    /// let timer = TimerWheel::with_defaults();
790    /// let handles = timer.allocate_handles(3);
791    /// let tasks: Vec<_> = (0..3)
792    ///     .map(|_| TimerTask::new_oneshot(Duration::from_secs(1), None))
793    ///     .collect();
794    /// let mut batch = timer.register_batch(handles, tasks).unwrap();
795    ///
796    /// // Postpone each timer with different delays and callbacks
797    /// let updates = vec![
798    ///     (Duration::from_secs(2), Some(CallbackWrapper::new(|| async {}))),
799    ///     (Duration::from_secs(3), None),
800    ///     (Duration::from_secs(4), Some(CallbackWrapper::new(|| async {}))),
801    /// ];
802    /// let postponed = batch.postpone_each_with_callbacks(updates).unwrap();
803    /// println!("Postponed {} timers", postponed);
804    /// # }
805    /// ```
806    #[inline]
807    pub fn postpone_each_with_callbacks(
808        &mut self,
809        updates: Vec<(std::time::Duration, Option<crate::task::CallbackWrapper>)>,
810    ) -> Result<usize, TimerError> {
811        self.handles.postpone_each_with_callbacks(updates)
812    }
813}
814
815/// Implement IntoIterator to allow direct iteration over BatchHandleWithCompletion
816///
817/// 实现 IntoIterator 以允许直接迭代 BatchHandleWithCompletion
818///
819/// # Examples (示例)
820/// ```no_run
821/// # use kestrel_timer::{TimerWheel, CallbackWrapper, TimerTask};
822/// # use std::time::Duration;
823/// #
824/// # #[tokio::main]
825/// # async fn main() {
826/// let timer = TimerWheel::with_defaults();
827/// let handles = timer.allocate_handles(3);
828/// let tasks: Vec<_> = (0..3)
829///     .map(|_| TimerTask::new_oneshot(Duration::from_secs(1), None))
830///     .collect();
831/// let batch = timer.register_batch(handles, tasks).unwrap();
832///
833/// // Iterate directly, each element is an independent TimerHandleWithCompletion
834/// // 直接迭代,每个元素是一个独立的 TimerHandleWithCompletion
835/// for handle in batch {
836///     // Can operate each handle individually
837///     // 可以单独操作每个句柄
838/// }
839/// # }
840/// ```
841impl IntoIterator for BatchHandleWithCompletion {
842    type Item = TimerHandleWithCompletion;
843    type IntoIter = BatchHandleWithCompletionIter;
844
845    #[inline]
846    fn into_iter(self) -> Self::IntoIter {
847        BatchHandleWithCompletionIter {
848            task_ids: self.handles.task_ids.into_iter(),
849            completion_rxs: self.completion_rxs.into_iter(),
850            wheel: self.handles.wheel,
851        }
852    }
853}
854
855/// Iterator for BatchHandleWithCompletion
856///
857/// BatchHandleWithCompletion 的迭代器
858pub struct BatchHandleWithCompletionIter {
859    task_ids: std::vec::IntoIter<TaskId>,
860    completion_rxs: std::vec::IntoIter<CompletionReceiver>,
861    wheel: Arc<Mutex<Wheel>>,
862}
863
864impl Iterator for BatchHandleWithCompletionIter {
865    type Item = TimerHandleWithCompletion;
866
867    #[inline]
868    fn next(&mut self) -> Option<Self::Item> {
869        match (self.task_ids.next(), self.completion_rxs.next()) {
870            (Some(task_id), Some(rx)) => Some(TimerHandleWithCompletion::new(
871                TimerHandle::new(task_id, self.wheel.clone()),
872                rx,
873            )),
874            _ => None,
875        }
876    }
877
878    #[inline]
879    fn size_hint(&self) -> (usize, Option<usize>) {
880        self.task_ids.size_hint()
881    }
882}
883
884impl ExactSizeIterator for BatchHandleWithCompletionIter {
885    #[inline]
886    fn len(&self) -> usize {
887        self.task_ids.len()
888    }
889}