kestrel_timer/timer/
handle.rs

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