kestrel-timer 0.3.6

High-performance async timer library based on Hierarchical Timing Wheel algorithm
Documentation
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
use crate::task::{CompletionReceiver, TaskId};
use crate::wheel::Wheel;
use parking_lot::Mutex;
use std::sync::Arc;

/// Timer handle for managing timer lifecycle (without completion receiver)
///
/// Note: This type does not implement Clone to prevent duplicate cancellation of the same timer. Each timer should have only one owner.
///
/// 定时器句柄,用于管理定时器生命周期(不含完成通知接收器)
///
/// 注意:此类型未实现 Clone 以防止重复取消同一定时器。每个定时器应该只有一个所有者。
pub struct TimerHandle {
    pub(crate) task_id: TaskId,
    pub(crate) wheel: Arc<Mutex<Wheel>>,
}

impl TimerHandle {
    #[inline]
    pub(crate) fn new(task_id: TaskId, wheel: Arc<Mutex<Wheel>>) -> Self {
        Self { task_id, wheel }
    }

    /// Cancel the timer
    ///
    /// # Returns
    /// Returns true if task exists and is successfully cancelled, otherwise false
    ///
    /// 取消定时器
    ///
    /// # 返回值
    /// 如果任务存在且成功取消则返回 true,否则返回 false
    ///
    /// # Examples (示例)
    /// ```no_run
    /// # use kestrel_timer::{TimerWheel, CallbackWrapper, TimerTask};
    /// # use std::time::Duration;
    /// #
    /// # #[tokio::main]
    /// # async fn main() {
    /// let timer = TimerWheel::with_defaults();
    /// let callback = Some(CallbackWrapper::new(|| async {}));
    /// let task = TimerTask::new_oneshot(Duration::from_secs(1), callback);
    /// let allocated_handle = timer.allocate_handle();
    /// let handle = timer.register(allocated_handle, task);
    ///
    /// // Cancel the timer
    /// let success = handle.cancel();
    /// println!("Canceled successfully: {}", success);
    /// # }
    /// ```
    #[inline]
    pub fn cancel(&self) -> bool {
        let mut wheel = self.wheel.lock();
        wheel.cancel(self.task_id)
    }

    /// Postpone the timer
    ///
    /// # Parameters
    /// - `new_delay`: New delay duration, recalculated from current time
    /// - `callback`: New callback function, pass `None` to keep original callback, pass `Some` to replace with new callback
    ///
    /// # Returns
    /// Returns true if task exists and is successfully postponed, otherwise false
    ///
    /// 推迟定时器
    ///
    /// # 参数
    /// - `new_delay`: 新的延迟时间,从当前时间重新计算
    /// - `callback`: 新的回调函数,传递 `None` 保持原始回调,传递 `Some` 替换为新的回调
    ///
    /// # 返回值
    /// 如果任务存在且成功推迟则返回 true,否则返回 false
    ///
    /// # Examples (示例)
    /// ```no_run
    /// # use kestrel_timer::{TimerWheel, CallbackWrapper, TimerTask};
    /// # use std::time::Duration;
    /// #
    /// # #[tokio::main]
    /// # async fn main() {
    /// let timer = TimerWheel::with_defaults();
    /// let callback = Some(CallbackWrapper::new(|| async {}));
    /// let task = TimerTask::new_oneshot(Duration::from_secs(1), callback);
    /// let allocated_handle = timer.allocate_handle();
    /// let handle = timer.register(allocated_handle, task);
    ///
    /// // Postpone to 5 seconds
    /// let success = handle.postpone(Duration::from_secs(5), None);
    /// println!("Postponed successfully: {}", success);
    /// # }
    /// ```
    #[inline]
    pub fn postpone(
        &self,
        new_delay: std::time::Duration,
        callback: Option<crate::task::CallbackWrapper>,
    ) -> bool {
        let mut wheel = self.wheel.lock();
        wheel.postpone(self.task_id, new_delay, callback)
    }
}

/// Timer handle with completion receiver for managing timer lifecycle
///
/// Note: This type does not implement Clone to prevent duplicate cancellation of the same timer. Each timer should have only one owner.
///
/// 包含完成通知接收器的定时器句柄,用于管理定时器生命周期
///
/// 注意:此类型未实现 Clone 以防止重复取消同一定时器。每个定时器应该只有一个所有者。
pub struct TimerHandleWithCompletion {
    handle: TimerHandle,
    pub(crate) completion_rx: CompletionReceiver,
}

impl TimerHandleWithCompletion {
    pub(crate) fn new(handle: TimerHandle, completion_rx: CompletionReceiver) -> Self {
        Self {
            handle,
            completion_rx,
        }
    }

    /// Cancel the timer
    ///
    /// # Returns
    /// Returns true if task exists and is successfully cancelled, otherwise false
    ///
    /// 取消定时器
    ///
    /// # 返回值
    /// 如果任务存在且成功取消则返回 true,否则返回 false
    ///
    /// # Examples (示例)
    /// ```no_run
    /// # use kestrel_timer::{TimerWheel, CallbackWrapper, TimerTask};
    /// # use std::time::Duration;
    /// #
    /// # #[tokio::main]
    /// # async fn main() {
    /// let timer = TimerWheel::with_defaults();
    /// let callback = Some(CallbackWrapper::new(|| async {}));
    /// let task = TimerTask::new_oneshot(Duration::from_secs(1), callback);
    /// let allocated_handle = timer.allocate_handle();
    /// let handle = timer.register(allocated_handle, task);
    ///
    /// // Cancel the timer
    /// let success = handle.cancel();
    /// println!("Canceled successfully: {}", success);
    /// # }
    /// ```
    pub fn cancel(&self) -> bool {
        self.handle.cancel()
    }

    /// Postpone the timer
    ///
    /// # Parameters
    /// - `new_delay`: New delay duration, recalculated from current time
    /// - `callback`: New callback function, pass `None` to keep original callback, pass `Some` to replace with new callback
    ///
    /// # Returns
    /// Returns true if task exists and is successfully postponed, otherwise false
    ///
    /// 推迟定时器
    ///
    /// # 参数
    /// - `new_delay`: 新的延迟时间,从当前时间重新计算
    /// - `callback`: 新的回调函数,传递 `None` 保持原始回调,传递 `Some` 替换为新的回调
    ///
    /// # 返回值
    /// 如果任务存在且成功推迟则返回 true,否则返回 false
    ///
    /// # Examples (示例)
    /// ```no_run
    /// # use kestrel_timer::{TimerWheel, CallbackWrapper, TimerTask};
    /// # use std::time::Duration;
    /// #
    /// # #[tokio::main]
    /// # async fn main() {
    /// let timer = TimerWheel::with_defaults();
    /// let callback = Some(CallbackWrapper::new(|| async {}));
    /// let task = TimerTask::new_oneshot(Duration::from_secs(1), callback);
    /// let allocated_handle = timer.allocate_handle();
    /// let handle = timer.register(allocated_handle, task);
    ///
    /// // Postpone to 5 seconds
    /// let success = handle.postpone(Duration::from_secs(5), None);
    /// println!("Postponed successfully: {}", success);
    /// # }
    /// ```
    pub fn postpone(
        &self,
        new_delay: std::time::Duration,
        callback: Option<crate::task::CallbackWrapper>,
    ) -> bool {
        self.handle.postpone(new_delay, callback)
    }

    /// Split handle into completion receiver and timer handle
    ///
    /// 将句柄拆分为完成通知接收器和定时器句柄
    ///
    /// # Examples (示例)
    /// ```no_run
    /// # use kestrel_timer::{TimerWheel, CallbackWrapper, TimerTask};
    /// # use std::time::Duration;
    /// #
    /// # #[tokio::main]
    /// # async fn main() {
    /// let timer = TimerWheel::with_defaults();
    /// let callback = Some(CallbackWrapper::new(|| async {
    ///     println!("Timer fired!");
    /// }));
    /// let task = TimerTask::new_oneshot(Duration::from_secs(1), callback);
    /// let allocated_handle = timer.allocate_handle();
    /// let handle = timer.register(allocated_handle, task);
    ///
    /// // Split into receiver and handle
    /// // 拆分为接收器和句柄
    /// let (rx, handle) = handle.into_parts();
    ///
    /// // Wait for timer completion
    /// // 等待定时器完成
    /// use kestrel_timer::CompletionReceiver;
    /// match rx {
    ///     CompletionReceiver::OneShot(receiver) => {
    ///         receiver.recv().await.unwrap();
    ///     },
    ///     _ => {}
    /// }
    /// println!("Timer completed!");
    /// # }
    /// ```
    pub fn into_parts(self) -> (CompletionReceiver, TimerHandle) {
        (self.completion_rx, self.handle)
    }
}

/// Batch timer handle for managing batch-scheduled timers (without completion receivers)
///
/// 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.
///
/// 批量定时器句柄,用于管理批量调度的定时器(不含完成通知接收器)
///
/// 注意:此类型未实现 Clone 以防止重复取消同一批定时器。使用 `into_iter()` 或 `into_handles()` 访问单个定时器句柄。
pub struct BatchHandle {
    pub(crate) task_ids: Vec<TaskId>,
    pub(crate) wheel: Arc<Mutex<Wheel>>,
}

impl BatchHandle {
    #[inline]
    pub(crate) fn new(task_ids: Vec<TaskId>, wheel: Arc<Mutex<Wheel>>) -> Self {
        Self { task_ids, wheel }
    }

    /// Cancel all timers in batch
    ///
    /// # Returns
    /// Number of successfully cancelled tasks
    ///
    /// 批量取消所有定时器
    ///
    /// # 返回值
    /// 成功取消的任务数量
    ///
    /// # Examples (示例)
    /// ```no_run
    /// # use kestrel_timer::{TimerWheel, CallbackWrapper, TimerTask};
    /// # use std::time::Duration;
    /// #
    /// # #[tokio::main]
    /// # async fn main() {
    /// let timer = TimerWheel::with_defaults();
    /// let handles = timer.allocate_handles(10);
    /// let tasks: Vec<_> = (0..10)
    ///     .map(|_| TimerTask::new_oneshot(Duration::from_secs(1), None))
    ///     .collect();
    /// let batch = timer.register_batch(handles, tasks).unwrap();
    ///
    /// let cancelled = batch.cancel_all();
    /// println!("Canceled {} timers", cancelled);
    /// # }
    /// ```
    #[inline]
    pub fn cancel_all(self) -> usize {
        let mut wheel = self.wheel.lock();
        wheel.cancel_batch(&self.task_ids)
    }

    /// Convert batch handle to Vec of individual timer handles
    ///
    /// Consumes BatchHandle and creates independent TimerHandle for each task
    ///
    /// 将批量句柄转换为单个定时器句柄的 Vec
    ///
    /// 消费 BatchHandle 并为每个任务创建独立的 TimerHandle
    ///
    /// # Examples (示例)
    /// ```no_run
    /// # use kestrel_timer::{TimerWheel, CallbackWrapper, TimerTask};
    /// # use std::time::Duration;
    /// #
    /// # #[tokio::main]
    /// # async fn main() {
    /// let timer = TimerWheel::with_defaults();
    /// let handles = timer.allocate_handles(3);
    /// let tasks: Vec<_> = (0..3)
    ///     .map(|_| TimerTask::new_oneshot(Duration::from_secs(1), None))
    ///     .collect();
    /// let batch = timer.register_batch(handles, tasks).unwrap();
    ///
    /// // Convert to individual handles
    /// // 转换为单个句柄
    /// let handles = batch.into_handles();
    /// for handle in handles {
    ///     // Can operate each handle individually
    ///     // 可以单独操作每个句柄
    /// }
    /// # }
    /// ```
    #[inline]
    pub fn into_handles(self) -> Vec<TimerHandle> {
        self.task_ids
            .into_iter()
            .map(|task_id| TimerHandle::new(task_id, self.wheel.clone()))
            .collect()
    }

    /// Get the number of batch tasks
    ///
    /// 获取批量任务数量
    #[inline]
    pub fn len(&self) -> usize {
        self.task_ids.len()
    }

    /// Check if batch tasks are empty
    ///
    /// 检查批量任务是否为空
    #[inline]
    pub fn is_empty(&self) -> bool {
        self.task_ids.is_empty()
    }

    /// Get reference to all task IDs
    ///
    /// 获取所有任务 ID 的引用
    #[inline]
    pub fn task_ids(&self) -> &[TaskId] {
        &self.task_ids
    }

    /// Batch postpone timers (keep original callbacks)
    ///
    /// # Parameters
    /// - `new_delay`: New delay duration applied to all timers
    ///
    /// # Returns
    /// Number of successfully postponed tasks
    ///
    /// 批量推迟定时器 (保持原始回调)
    ///
    /// # 参数
    /// - `new_delay`: 应用于所有定时器的新延迟时间
    ///
    /// # 返回值
    /// 成功推迟的任务数量
    ///
    /// # Examples (示例)
    /// ```no_run
    /// # use kestrel_timer::{TimerWheel, CallbackWrapper};
    /// # use std::time::Duration;
    /// #
    /// # #[tokio::main]
    /// # async fn main() {
    /// # use kestrel_timer::TimerTask;
    /// let timer = TimerWheel::with_defaults();
    /// let handles = timer.allocate_handles(10);
    /// let tasks: Vec<_> = (0..10)
    ///     .map(|_| TimerTask::new_oneshot(Duration::from_secs(1), None))
    ///     .collect();
    /// let batch_with_completion = timer.register_batch(handles, tasks).unwrap();
    /// let (rxs, batch) = batch_with_completion.into_parts();
    ///
    /// // Postpone all timers to 5 seconds
    /// let postponed = batch.postpone_all(Duration::from_secs(5));
    /// println!("Postponed {} timers", postponed);
    /// # }
    /// ```
    #[inline]
    pub fn postpone_all(self, new_delay: std::time::Duration) -> usize {
        let updates: Vec<_> = self.task_ids.iter().map(|&id| (id, new_delay)).collect();
        let mut wheel = self.wheel.lock();
        wheel.postpone_batch(updates)
    }

    /// Batch postpone timers with individual delays (keep original callbacks)
    ///
    /// # Parameters
    /// - `delays`: List of new delay durations for each timer (must match the number of tasks)
    ///
    /// # Returns
    /// Number of successfully postponed tasks
    ///
    /// 批量推迟定时器,每个定时器使用不同延迟 (保持原始回调)
    ///
    /// # 参数
    /// - `delays`: 每个定时器的新延迟时间列表(必须与任务数量匹配)
    ///
    /// # 返回值
    /// 成功推迟的任务数量
    ///
    /// # Examples (示例)
    /// ```no_run
    /// # use kestrel_timer::{TimerWheel, CallbackWrapper, TimerTask};
    /// # use std::time::Duration;
    /// #
    /// # #[tokio::main]
    /// # async fn main() {
    /// let timer = TimerWheel::with_defaults();
    /// let handles = timer.allocate_handles(3);
    /// let tasks: Vec<_> = (0..3)
    ///     .map(|_| TimerTask::new_oneshot(Duration::from_secs(1), None))
    ///     .collect();
    /// let batch_with_completion = timer.register_batch(handles, tasks).unwrap();
    /// let (rxs, batch) = batch_with_completion.into_parts();
    ///
    /// // Postpone each timer with different delays
    /// let new_delays = vec![
    ///     Duration::from_secs(2),
    ///     Duration::from_secs(3),
    ///     Duration::from_secs(4),
    /// ];
    /// let postponed = batch.postpone_each(new_delays);
    /// println!("Postponed {} timers", postponed);
    /// # }
    /// ```
    #[inline]
    pub fn postpone_each(self, delays: Vec<std::time::Duration>) -> usize {
        let updates: Vec<_> = self.task_ids.into_iter().zip(delays).collect();
        let mut wheel = self.wheel.lock();
        wheel.postpone_batch(updates)
    }

    /// Batch postpone timers with individual delays and callbacks
    ///
    /// # Parameters
    /// - `updates`: List of tuples of (new delay, new callback) for each timer
    ///
    /// # Returns
    /// Number of successfully postponed tasks
    ///
    /// 批量推迟定时器,每个定时器使用不同延迟和回调
    ///
    /// # 参数
    /// - `updates`: 每个定时器的 (新延迟, 新回调) 元组列表
    ///
    /// # 返回值
    /// 成功推迟的任务数量
    ///
    /// # Examples (示例)
    /// ```no_run
    /// # use kestrel_timer::{TimerWheel, CallbackWrapper, TimerTask};
    /// # use std::time::Duration;
    /// #
    /// # #[tokio::main]
    /// # async fn main() {
    /// let timer = TimerWheel::with_defaults();
    /// let handles = timer.allocate_handles(3);
    /// let tasks: Vec<_> = (0..3)
    ///     .map(|_| TimerTask::new_oneshot(Duration::from_secs(1), None))
    ///     .collect();
    /// let batch_with_completion = timer.register_batch(handles, tasks).unwrap();
    /// let (rxs, batch) = batch_with_completion.into_parts();
    ///
    /// // Postpone each timer with different delays and callbacks
    /// let updates = vec![
    ///     (Duration::from_secs(2), Some(CallbackWrapper::new(|| async {}))),
    ///     (Duration::from_secs(3), None),
    ///     (Duration::from_secs(4), Some(CallbackWrapper::new(|| async {}))),
    /// ];
    /// let postponed = batch.postpone_each_with_callbacks(updates);
    /// println!("Postponed {} timers", postponed);
    /// # }
    /// ```
    #[inline]
    pub fn postpone_each_with_callbacks(
        self,
        updates: Vec<(std::time::Duration, Option<crate::task::CallbackWrapper>)>,
    ) -> usize {
        let updates_with_ids: Vec<_> = self
            .task_ids
            .into_iter()
            .zip(updates)
            .map(|(id, (delay, callback))| (id, delay, callback))
            .collect();
        let mut wheel = self.wheel.lock();
        wheel.postpone_batch_with_callbacks(updates_with_ids)
    }
}

/// Batch timer handle with completion receivers for managing batch-scheduled timers
///
/// 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.
///
/// 包含完成通知接收器的批量定时器句柄,用于管理批量调度的定时器
///
/// 注意:此类型未实现 Clone 以防止重复取消同一批定时器。使用 `into_iter()` 或 `into_handles()` 访问单个定时器句柄。
pub struct BatchHandleWithCompletion {
    handles: BatchHandle,
    completion_rxs: Vec<CompletionReceiver>,
}

impl BatchHandleWithCompletion {
    #[inline]
    pub(crate) fn new(handles: BatchHandle, completion_rxs: Vec<CompletionReceiver>) -> Self {
        Self {
            handles,
            completion_rxs,
        }
    }

    /// Cancel all timers in batch
    ///
    /// # Returns
    /// Number of successfully cancelled tasks
    ///
    /// 批量取消所有定时器
    ///
    /// # 返回值
    /// 成功取消的任务数量
    ///
    /// # Examples (示例)
    /// ```no_run
    /// # use kestrel_timer::{TimerWheel, CallbackWrapper, TimerTask};
    /// # use std::time::Duration;
    /// #
    /// # #[tokio::main]
    /// # async fn main() {
    /// let timer = TimerWheel::with_defaults();
    /// let handles = timer.allocate_handles(10);
    /// let tasks: Vec<_> = (0..10)
    ///     .map(|_| TimerTask::new_oneshot(Duration::from_secs(1), None))
    ///     .collect();
    /// let batch = timer.register_batch(handles, tasks).unwrap();
    ///
    /// let cancelled = batch.cancel_all();
    /// println!("Canceled {} timers", cancelled);
    /// # }
    /// ```
    #[inline]
    pub fn cancel_all(self) -> usize {
        self.handles.cancel_all()
    }

    /// Convert batch handle to Vec of individual timer handles with completion receivers
    ///
    /// Consumes BatchHandleWithCompletion and creates independent TimerHandleWithCompletion for each task
    ///
    /// 将批量句柄转换为单个定时器句柄的 Vec
    ///
    /// 消费 BatchHandleWithCompletion 并为每个任务创建独立的 TimerHandleWithCompletion
    ///
    /// # Examples (示例)
    /// ```no_run
    /// # use kestrel_timer::{TimerWheel, CallbackWrapper, TimerTask};
    /// # use std::time::Duration;
    /// #
    /// # #[tokio::main]
    /// # async fn main() {
    /// let timer = TimerWheel::with_defaults();
    /// let handles = timer.allocate_handles(3);
    /// let tasks: Vec<_> = (0..3)
    ///     .map(|_| TimerTask::new_oneshot(Duration::from_secs(1), None))
    ///     .collect();
    /// let batch = timer.register_batch(handles, tasks).unwrap();
    ///
    /// // Convert to individual handles
    /// // 转换为单个句柄
    /// let handles = batch.into_handles();
    /// for handle in handles {
    ///     // Can operate each handle individually
    ///     // 可以单独操作每个句柄
    /// }
    /// # }
    /// ```
    #[inline]
    pub fn into_handles(self) -> Vec<TimerHandleWithCompletion> {
        self.handles
            .into_handles()
            .into_iter()
            .zip(self.completion_rxs)
            .map(|(handle, rx)| TimerHandleWithCompletion::new(handle, rx))
            .collect()
    }

    /// Get the number of batch tasks
    ///
    /// 获取批量任务数量
    #[inline]
    pub fn len(&self) -> usize {
        self.handles.len()
    }

    /// Check if batch tasks are empty
    ///
    /// 检查批量任务是否为空
    #[inline]
    pub fn is_empty(&self) -> bool {
        self.handles.is_empty()
    }

    /// Get reference to all task IDs
    ///
    /// 获取所有任务 ID 的引用
    #[inline]
    pub fn task_ids(&self) -> &[TaskId] {
        self.handles.task_ids()
    }

    /// Split batch handle into completion receivers and batch handle
    ///
    /// 将批量句柄拆分为完成通知接收器列表和批量句柄
    ///
    /// # Examples (示例)
    /// ```no_run
    /// # use kestrel_timer::{TimerWheel, CallbackWrapper, TimerTask};
    /// # use std::time::Duration;
    /// #
    /// # #[tokio::main]
    /// # async fn main() {
    /// let timer = TimerWheel::with_defaults();
    /// let handles = timer.allocate_handles(3);
    /// let tasks: Vec<_> = (0..3)
    ///     .map(|_| TimerTask::new_oneshot(Duration::from_secs(1), None))
    ///     .collect();
    /// let batch = timer.register_batch(handles, tasks).unwrap();
    ///
    /// // Split into receivers and handle
    /// // 拆分为接收器和句柄
    /// use kestrel_timer::CompletionReceiver;
    /// let (receivers, batch_handle) = batch.into_parts();
    /// for rx in receivers {
    ///     tokio::spawn(async move {
    ///         match rx {
    ///             CompletionReceiver::OneShot(receiver) => {
    ///                 receiver.recv().await.unwrap();
    ///                 println!("A timer completed!");
    ///             },
    ///             _ => {}
    ///         }
    ///     });
    /// }
    /// # }
    /// ```
    #[inline]
    pub fn into_parts(self) -> (Vec<CompletionReceiver>, BatchHandle) {
        let handle = BatchHandle::new(self.handles.task_ids.clone(), self.handles.wheel);
        (self.completion_rxs, handle)
    }

    /// Batch postpone timers (keep original callbacks)
    ///
    /// # Parameters
    /// - `new_delay`: New delay duration applied to all timers
    ///
    /// # Returns
    /// Number of successfully postponed tasks
    ///
    /// 批量推迟定时器 (保持原始回调)
    ///
    /// # 参数
    /// - `new_delay`: 应用于所有定时器的新延迟时间
    ///
    /// # 返回值
    /// 成功推迟的任务数量
    ///
    /// # Examples (示例)
    /// ```no_run
    /// # use kestrel_timer::{TimerWheel, CallbackWrapper, TimerTask};
    /// # use std::time::Duration;
    /// #
    /// # #[tokio::main]
    /// # async fn main() {
    /// let timer = TimerWheel::with_defaults();
    /// let handles = timer.allocate_handles(10);
    /// let tasks: Vec<_> = (0..10)
    ///     .map(|_| TimerTask::new_oneshot(Duration::from_secs(1), None))
    ///     .collect();
    /// let batch = timer.register_batch(handles, tasks).unwrap();
    ///
    /// // Postpone all timers to 5 seconds
    /// let postponed = batch.postpone_all(Duration::from_secs(5));
    /// println!("Postponed {} timers", postponed);
    /// # }
    /// ```
    #[inline]
    pub fn postpone_all(self, new_delay: std::time::Duration) -> usize {
        self.handles.postpone_all(new_delay)
    }

    /// Batch postpone timers with individual delays (keep original callbacks)
    ///
    /// # Parameters
    /// - `delays`: List of new delay durations for each timer (must match the number of tasks)
    ///
    /// # Returns
    /// Number of successfully postponed tasks
    ///
    /// 批量推迟定时器,每个定时器使用不同延迟 (保持原始回调)
    ///
    /// # 参数
    /// - `delays`: 每个定时器的新延迟时间列表(必须与任务数量匹配)
    ///
    /// # 返回值
    /// 成功推迟的任务数量
    ///
    /// # Examples (示例)
    /// ```no_run
    /// # use kestrel_timer::{TimerWheel, CallbackWrapper, TimerTask};
    /// # use std::time::Duration;
    /// #
    /// # #[tokio::main]
    /// # async fn main() {
    /// let timer = TimerWheel::with_defaults();
    /// let handles = timer.allocate_handles(3);
    /// let tasks: Vec<_> = (0..3)
    ///     .map(|_| TimerTask::new_oneshot(Duration::from_secs(1), None))
    ///     .collect();
    /// let batch = timer.register_batch(handles, tasks).unwrap();
    ///
    /// // Postpone each timer with different delays
    /// let new_delays = vec![
    ///     Duration::from_secs(2),
    ///     Duration::from_secs(3),
    ///     Duration::from_secs(4),
    /// ];
    /// let postponed = batch.postpone_each(new_delays);
    /// println!("Postponed {} timers", postponed);
    /// # }
    /// ```
    #[inline]
    pub fn postpone_each(self, delays: Vec<std::time::Duration>) -> usize {
        self.handles.postpone_each(delays)
    }

    /// Batch postpone timers with individual delays and callbacks
    ///
    /// # Parameters
    /// - `updates`: List of tuples of (new delay, new callback) for each timer
    ///
    /// # Returns
    /// Number of successfully postponed tasks
    ///
    /// 批量推迟定时器,每个定时器使用不同延迟和回调
    ///
    /// # 参数
    /// - `updates`: 每个定时器的 (新延迟, 新回调) 元组列表
    ///
    /// # 返回值
    /// 成功推迟的任务数量
    ///
    /// # Examples (示例)
    /// ```no_run
    /// # use kestrel_timer::{TimerWheel, CallbackWrapper, TimerTask};
    /// # use std::time::Duration;
    /// #
    /// # #[tokio::main]
    /// # async fn main() {
    /// let timer = TimerWheel::with_defaults();
    /// let handles = timer.allocate_handles(3);
    /// let tasks: Vec<_> = (0..3)
    ///     .map(|_| TimerTask::new_oneshot(Duration::from_secs(1), None))
    ///     .collect();
    /// let batch = timer.register_batch(handles, tasks).unwrap();
    ///
    /// // Postpone each timer with different delays and callbacks
    /// let updates = vec![
    ///     (Duration::from_secs(2), Some(CallbackWrapper::new(|| async {}))),
    ///     (Duration::from_secs(3), None),
    ///     (Duration::from_secs(4), Some(CallbackWrapper::new(|| async {}))),
    /// ];
    /// let postponed = batch.postpone_each_with_callbacks(updates);
    /// println!("Postponed {} timers", postponed);
    /// # }
    /// ```
    #[inline]
    pub fn postpone_each_with_callbacks(
        self,
        updates: Vec<(std::time::Duration, Option<crate::task::CallbackWrapper>)>,
    ) -> usize {
        self.handles.postpone_each_with_callbacks(updates)
    }
}

/// Implement IntoIterator to allow direct iteration over BatchHandleWithCompletion
///
/// 实现 IntoIterator 以允许直接迭代 BatchHandleWithCompletion
///
/// # Examples (示例)
/// ```no_run
/// # use kestrel_timer::{TimerWheel, CallbackWrapper, TimerTask};
/// # use std::time::Duration;
/// #
/// # #[tokio::main]
/// # async fn main() {
/// let timer = TimerWheel::with_defaults();
/// let handles = timer.allocate_handles(3);
/// let tasks: Vec<_> = (0..3)
///     .map(|_| TimerTask::new_oneshot(Duration::from_secs(1), None))
///     .collect();
/// let batch = timer.register_batch(handles, tasks).unwrap();
///
/// // Iterate directly, each element is an independent TimerHandleWithCompletion
/// // 直接迭代,每个元素是一个独立的 TimerHandleWithCompletion
/// for handle in batch {
///     // Can operate each handle individually
///     // 可以单独操作每个句柄
/// }
/// # }
/// ```
impl IntoIterator for BatchHandleWithCompletion {
    type Item = TimerHandleWithCompletion;
    type IntoIter = BatchHandleWithCompletionIter;

    #[inline]
    fn into_iter(self) -> Self::IntoIter {
        BatchHandleWithCompletionIter {
            task_ids: self.handles.task_ids.into_iter(),
            completion_rxs: self.completion_rxs.into_iter(),
            wheel: self.handles.wheel,
        }
    }
}

/// Iterator for BatchHandleWithCompletion
///
/// BatchHandleWithCompletion 的迭代器
pub struct BatchHandleWithCompletionIter {
    task_ids: std::vec::IntoIter<TaskId>,
    completion_rxs: std::vec::IntoIter<CompletionReceiver>,
    wheel: Arc<Mutex<Wheel>>,
}

impl Iterator for BatchHandleWithCompletionIter {
    type Item = TimerHandleWithCompletion;

    #[inline]
    fn next(&mut self) -> Option<Self::Item> {
        match (self.task_ids.next(), self.completion_rxs.next()) {
            (Some(task_id), Some(rx)) => Some(TimerHandleWithCompletion::new(
                TimerHandle::new(task_id, self.wheel.clone()),
                rx,
            )),
            _ => None,
        }
    }

    #[inline]
    fn size_hint(&self) -> (usize, Option<usize>) {
        self.task_ids.size_hint()
    }
}

impl ExactSizeIterator for BatchHandleWithCompletionIter {
    #[inline]
    fn len(&self) -> usize {
        self.task_ids.len()
    }
}