kestrel_timer/timer/
handle.rs

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