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