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