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
// Copyright 2023 The RocketMQ Rust Authors
//
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
//
// http://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS IS" BASIS,
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
// See the License for the specific language governing permissions and
// limitations under the License.
pub mod executor;
pub mod scheduler;
pub mod task;
pub mod trigger;
use std::error::Error;
use std::fmt;
pub use executor::ExecutorPool;
pub use task::Task;
pub use task::TaskContext;
pub use task::TaskResult;
pub use task::TaskStatus;
/// Scheduler error type
#[derive(Debug)]
pub enum SchedulerError {
TaskNotFound(String),
TaskAlreadyExists(String),
ExecutorError(String),
TriggerError(String),
SystemError(String),
}
impl fmt::Display for SchedulerError {
fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
match self {
SchedulerError::TaskNotFound(id) => write!(f, "Task not found: {id}"),
SchedulerError::TaskAlreadyExists(id) => write!(f, "Task already exists: {id}"),
SchedulerError::ExecutorError(msg) => write!(f, "Executor error: {msg}"),
SchedulerError::TriggerError(msg) => write!(f, "Trigger error: {msg}"),
SchedulerError::SystemError(msg) => write!(f, "System error: {msg}"),
}
}
}
impl Error for SchedulerError {}
pub type SchedulerResult<T> = Result<T, SchedulerError>;
pub mod simple_scheduler {
use std::collections::HashMap;
use std::future::Future;
use std::sync::atomic::AtomicU64;
use std::sync::atomic::Ordering;
use std::sync::Arc;
use anyhow::Result;
use parking_lot::RwLock;
use tokio::sync::Semaphore;
use tokio::task::JoinHandle;
use tokio::time::Duration;
use tokio::time::Instant;
use tokio::time::{self};
use tokio_util::sync::CancellationToken;
use tracing::error;
use tracing::info;
use crate::ArcMut;
#[derive(Debug, Clone, Copy)]
pub enum ScheduleMode {
/// Align the beats, and they might pile up.
FixedRate,
/// Sleep only after the task is completed, and there will be no accumulation.
FixedDelay,
/// Align the beats, but skip if the last task is not yet completed.
FixedRateNoOverlap,
}
type TaskId = u64;
pub struct TaskInfo {
cancel_token: CancellationToken,
handle: JoinHandle<()>,
}
#[derive(Clone)]
pub struct ScheduledTaskManager {
tasks: Arc<RwLock<HashMap<TaskId, TaskInfo>>>,
counter: Arc<AtomicU64>,
}
impl Default for ScheduledTaskManager {
fn default() -> Self {
Self::new()
}
}
impl ScheduledTaskManager {
pub fn new() -> Self {
Self {
tasks: Arc::new(RwLock::new(HashMap::new())),
counter: Arc::new(AtomicU64::new(0)),
}
}
fn next_id(&self) -> TaskId {
self.counter.fetch_add(1, Ordering::Relaxed)
}
/// Adds a fixed-rate scheduled task to the task manager.
///
/// # Arguments
/// * `initial_delay` - The delay before the first execution of the task.
/// * `period` - The interval between task executions.
/// * `task_fn` - A function that defines the task to be executed. It takes a
/// `CancellationToken` as an argument and returns a `Future` that resolves to a
/// `Result<()>`.
///
/// # Returns
/// A `TaskId` representing the unique identifier of the scheduled task.
///
/// # Notes
/// - Tasks are executed at fixed intervals, even if previous executions overlap.
pub fn add_fixed_rate_task<F, Fut>(&self, initial_delay: Duration, period: Duration, task_fn: F) -> TaskId
where
F: FnMut(CancellationToken) -> Fut + Send + Sync + 'static,
Fut: Future<Output = Result<()>> + Send + 'static,
{
self.add_scheduled_task(ScheduleMode::FixedRate, initial_delay, period, task_fn)
}
/// Adds a fixed-delay scheduled task to the task manager.
///
/// # Arguments
/// * `initial_delay` - The delay before the first execution of the task.
/// * `period` - The interval between task executions.
/// * `task_fn` - A function that defines the task to be executed. It takes a
/// `CancellationToken` as an argument and returns a `Future` that resolves to a
/// `Result<()>`.
///
/// # Returns
/// A `TaskId` representing the unique identifier of the scheduled task.
///
/// # Notes
/// - Tasks are executed serially, with a delay after each task completes.
pub fn add_fixed_delay_task<F, Fut>(&self, initial_delay: Duration, period: Duration, task_fn: F) -> TaskId
where
F: FnMut(CancellationToken) -> Fut + Send + Sync + 'static,
Fut: Future<Output = Result<()>> + Send + 'static,
{
self.add_scheduled_task(ScheduleMode::FixedDelay, initial_delay, period, task_fn)
}
/// Adds a fixed-rate-no-overlap scheduled task to the task manager.
///
/// # Arguments
/// * `initial_delay` - The delay before the first execution of the task.
/// * `period` - The interval between task executions.
/// * `task_fn` - A function that defines the task to be executed. It takes a
/// `CancellationToken` as an argument and returns a `Future` that resolves to a
/// `Result<()>`.
///
/// # Returns
/// A `TaskId` representing the unique identifier of the scheduled task.
///
/// # Notes
/// - Tasks are executed at fixed intervals, but overlapping executions are skipped.
pub fn add_fixed_rate_no_overlap_task<F, Fut>(
&self,
initial_delay: Duration,
period: Duration,
task_fn: F,
) -> TaskId
where
F: FnMut(CancellationToken) -> Fut + Send + Sync + 'static,
Fut: Future<Output = Result<()>> + Send + 'static,
{
self.add_scheduled_task(ScheduleMode::FixedRateNoOverlap, initial_delay, period, task_fn)
}
/// Adds a scheduled task to the task manager.
///
/// # Arguments
/// * `mode` - The scheduling mode for the task. Determines how the task is executed:
/// - `FixedRate`: Aligns the beats, allowing tasks to pile up if they take too long.
/// - `FixedDelay`: Executes tasks serially, with a delay after each task completes.
/// - `FixedRateNoOverlap`: Aligns the beats but skips execution if the previous task is
/// still running.
/// * `initial_delay` - The delay before the first execution of the task.
/// * `period` - The interval between task executions.
/// * `task_fn` - A function that defines the task to be executed. It takes a
/// `CancellationToken` as an argument and returns a `Future` that resolves to a
/// `Result<()>`.
///
/// # Returns
/// A `TaskId` representing the unique identifier of the scheduled task.
///
/// # Notes
/// - The task function is executed asynchronously.
/// - The `CancellationToken` can be used to gracefully cancel the task.
/// - The task is added to the internal task manager and can be managed (e.g., canceled or
/// aborted) later.
pub fn add_scheduled_task<F, Fut>(
&self,
mode: ScheduleMode,
initial_delay: Duration,
period: Duration,
task_fn: F,
) -> TaskId
where
F: FnMut(CancellationToken) -> Fut + Send + Sync + 'static,
Fut: Future<Output = Result<()>> + Send + 'static,
{
let id = self.next_id();
let token = CancellationToken::new();
let token_child = token.clone();
let task_fn = ArcMut::new(task_fn);
let handle = tokio::spawn({
let mut task_fn = task_fn;
async move {
match mode {
ScheduleMode::FixedRate => {
let start = Instant::now() + initial_delay;
let mut ticker = time::interval_at(start, period);
loop {
tokio::select! {
_ = token_child.cancelled() => {
info!("Task {} cancelled gracefully", id);
break;
}
_ = ticker.tick() => {
// Allow concurrent execution: One subtask per tick
let mut task_fn = task_fn.clone();
let child = token_child.clone();
tokio::spawn(async move {
// 1) Lock out &mut F, call once to get a future
let fut = {
(task_fn)(child)
};
// The lock has been released. Awaiting here ensures the lock doesn't cross await boundaries.
if let Err(e) = fut.await {
error!("FixedRate task {} failed: {:?}", id, e);
}
});
}
}
}
}
ScheduleMode::FixedDelay => {
time::sleep(initial_delay).await;
loop {
tokio::select! {
_ = token_child.cancelled() => {
info!("Task {} cancelled gracefully", id);
break;
}
_ = async {
// Serial execution: complete one task and then sleep
let fut = {
(task_fn)(token_child.clone())
};
if let Err(e) = fut.await {
error!("FixedDelay task {} failed: {:?}", id, e);
}
time::sleep(period).await;
} => {}
}
}
}
ScheduleMode::FixedRateNoOverlap => {
let start = Instant::now() + initial_delay;
let mut ticker = time::interval_at(start, period);
// Permission=1, controls non-overlapping execution
let gate = Arc::new(Semaphore::new(1));
loop {
tokio::select! {
_ = token_child.cancelled() => {
info!("Task {} cancelled gracefully", id);
break;
}
_ = ticker.tick() => {
// Try to acquire permission. If unable to acquire, skip the current tick.
if let Ok(permit) = gate.clone().try_acquire_owned() {
let mut task_fn = task_fn.clone();
let child = token_child.clone();
tokio::spawn(async move {
// Release the lock immediately after generating the future
let fut = {
(task_fn)(child)
};
if let Err(e) = fut.await {
error!("FixedRateNoOverlap task {} failed: {:?}", id, e);
}
drop(permit); // Release the permit after completion
});
} else {
info!("Task {} skipped due to overlap", id);
}
}
}
}
}
}
}
});
self.tasks.write().insert(
id,
TaskInfo {
cancel_token: token,
handle,
},
);
id
}
/// Graceful cancellation
pub fn cancel_task(&self, id: TaskId) {
if let Some(info) = self.tasks.write().remove(&id) {
info.cancel_token.cancel();
tokio::spawn(async move {
let _ = info.handle.await;
});
}
}
/// Roughly abort
pub fn abort_task(&self, id: TaskId) {
if let Some(info) = self.tasks.write().remove(&id) {
info.handle.abort();
}
}
/// Batch cancel
pub fn cancel_all(&self) {
let mut tasks = self.tasks.write();
for (_, info) in tasks.drain() {
info.cancel_token.cancel();
tokio::spawn(async move {
let _ = info.handle.await;
});
}
}
/// Batch abort
pub fn abort_all(&self) {
let mut tasks = self.tasks.write();
for (_, info) in tasks.drain() {
info.handle.abort();
}
}
pub fn task_count(&self) -> usize {
self.tasks.read().len()
}
}
impl ScheduledTaskManager {
/// Adds a fixed-rate scheduled task to the task manager asynchronously.
///
/// # Arguments
/// * `initial_delay` - The delay before the first execution of the task.
/// * `period` - The interval between task executions.
/// * `task_fn` - A function that defines the task to be executed. It takes a
/// `CancellationToken` as an argument and returns a `Result<()>`.
///
/// # Returns
/// A `TaskId` representing the unique identifier of the scheduled task.
///
/// # Notes
/// - Tasks are executed at fixed intervals, even if previous executions overlap.
/// - The task function is executed asynchronously.
pub fn add_fixed_rate_task_async<F>(&self, initial_delay: Duration, period: Duration, task_fn: F) -> TaskId
where
F: AsyncFnMut(CancellationToken) -> Result<()> + Send + Sync + 'static,
for<'a> <F as AsyncFnMut<(CancellationToken,)>>::CallRefFuture<'a>: Send,
{
self.add_scheduled_task_async(ScheduleMode::FixedRate, initial_delay, period, task_fn)
}
/// Adds a fixed-delay scheduled task to the task manager asynchronously.
///
/// # Arguments
/// * `initial_delay` - The delay before the first execution of the task.
/// * `period` - The interval between task executions.
/// * `task_fn` - A function that defines the task to be executed. It takes a
/// `CancellationToken` as an argument and returns a `Result<()>`.
///
/// # Returns
/// A `TaskId` representing the unique identifier of the scheduled task.
///
/// # Notes
/// - Tasks are executed serially, with a delay after each task completes.
/// - The task function is executed asynchronously.
pub fn add_fixed_delay_task_async<F>(&self, initial_delay: Duration, period: Duration, task_fn: F) -> TaskId
where
F: AsyncFnMut(CancellationToken) -> Result<()> + Send + Sync + 'static,
for<'a> <F as AsyncFnMut<(CancellationToken,)>>::CallRefFuture<'a>: Send,
{
self.add_scheduled_task_async(ScheduleMode::FixedDelay, initial_delay, period, task_fn)
}
/// Adds a fixed-rate-no-overlap scheduled task to the task manager asynchronously.
///
/// # Arguments
/// * `initial_delay` - The delay before the first execution of the task.
/// * `period` - The interval between task executions.
/// * `task_fn` - A function that defines the task to be executed. It takes a
/// `CancellationToken` as an argument and returns a `Result<()>`.
///
/// # Returns
/// A `TaskId` representing the unique identifier of the scheduled task.
///
/// # Notes
/// - Tasks are executed at fixed intervals, but overlapping executions are skipped.
/// - The task function is executed asynchronously.
pub fn add_fixed_rate_no_overlap_task_async<F>(
&self,
initial_delay: Duration,
period: Duration,
task_fn: F,
) -> TaskId
where
F: AsyncFnMut(CancellationToken) -> Result<()> + Send + Sync + 'static,
for<'a> <F as AsyncFnMut<(CancellationToken,)>>::CallRefFuture<'a>: Send,
{
self.add_scheduled_task_async(ScheduleMode::FixedRateNoOverlap, initial_delay, period, task_fn)
}
/// Adds a scheduled task to the task manager asynchronously.
///
/// # Arguments
/// * `mode` - The scheduling mode for the task. Determines how the task is executed:
/// - `FixedRate`: Aligns the beats, allowing tasks to pile up if they take too long.
/// - `FixedDelay`: Executes tasks serially, with a delay after each task completes.
/// - `FixedRateNoOverlap`: Aligns the beats but skips execution if the previous task is
/// still running.
/// * `initial_delay` - The delay before the first execution of the task.
/// * `period` - The interval between task executions.
/// * `task_fn` - A function that defines the task to be executed. It takes a
/// `CancellationToken` as an argument and returns a `Future` that resolves to a
/// `Result<()>`.
///
/// # Returns
/// A `TaskId` representing the unique identifier of the scheduled task.
///
/// # Notes
/// - The task function is executed asynchronously.
/// - The `CancellationToken` can be used to gracefully cancel the task.
/// - The task is added to the internal task manager and can be managed (e.g., canceled or
/// aborted) later.
pub fn add_scheduled_task_async<F>(
&self,
mode: ScheduleMode,
initial_delay: Duration,
period: Duration,
task_fn: F,
) -> TaskId
where
F: AsyncFnMut(CancellationToken) -> Result<()> + Send + Sync + 'static,
for<'a> <F as AsyncFnMut<(CancellationToken,)>>::CallRefFuture<'a>: Send,
{
let id = self.next_id();
let token = CancellationToken::new();
let token_child = token.clone();
let task_fn = ArcMut::new(task_fn);
let handle = tokio::spawn({
let mut task_fn = task_fn;
async move {
match mode {
ScheduleMode::FixedRate => {
let start = Instant::now() + initial_delay;
let mut ticker = time::interval_at(start, period);
loop {
tokio::select! {
_ = token_child.cancelled() => {
info!("Task {} cancelled gracefully", id);
break;
}
_ = ticker.tick() => {
// Allow concurrent execution: One subtask per tick
let mut task_fn = task_fn.clone();
let child = token_child.clone();
tokio::spawn(async move {
// 1) Lock out &mut F, call once to get a future
let fut = {
task_fn(child)
};
// The lock has been released. Awaiting here ensures the lock doesn't cross await boundaries.
if let Err(e) = fut.await {
error!("FixedRate task {} failed: {:?}", id, e);
}
});
}
}
}
}
ScheduleMode::FixedDelay => {
time::sleep(initial_delay).await;
loop {
tokio::select! {
_ = token_child.cancelled() => {
info!("Task {} cancelled gracefully", id);
break;
}
_ = async {
// Serial execution: complete one task and then sleep
let fut = {
(task_fn)(token_child.clone())
};
if let Err(e) = fut.await {
error!("FixedDelay task {} failed: {:?}", id, e);
}
time::sleep(period).await;
} => {}
}
}
}
ScheduleMode::FixedRateNoOverlap => {
let start = Instant::now() + initial_delay;
let mut ticker = time::interval_at(start, period);
// Permission=1, controls non-overlapping execution
let gate = Arc::new(Semaphore::new(1));
loop {
tokio::select! {
_ = token_child.cancelled() => {
info!("Task {} cancelled gracefully", id);
break;
}
_ = ticker.tick() => {
// Try to acquire permission. If unable to acquire, skip the current tick.
if let Ok(permit) = gate.clone().try_acquire_owned() {
let mut task_fn = task_fn.clone();
let child = token_child.clone();
tokio::spawn(async move {
// Release the lock immediately after generating the future
let fut = {
(task_fn)(child)
};
if let Err(e) = fut.await {
error!("FixedRateNoOverlap task {} failed: {:?}", id, e);
}
drop(permit); // Release the permit after completion
});
} else {
info!("Task {} skipped due to overlap", id);
}
}
}
}
}
}
}
});
self.tasks.write().insert(
id,
TaskInfo {
cancel_token: token,
handle,
},
);
id
}
}
}
#[cfg(test)]
mod tests {
use std::sync::atomic::AtomicUsize;
use std::sync::atomic::Ordering;
use std::sync::Arc;
use std::time::Duration;
use tokio::time;
use crate::schedule::simple_scheduler::*;
#[tokio::test]
async fn adds_task_and_increments_task_count() {
let manager = ScheduledTaskManager::new();
let task_id = manager.add_scheduled_task(
ScheduleMode::FixedRate,
Duration::from_secs(1),
Duration::from_secs(2),
|token| async move {
if token.is_cancelled() {
return Ok(());
}
Ok(())
},
);
assert_eq!(manager.task_count(), 1);
manager.cancel_task(task_id);
}
#[tokio::test]
async fn cancels_task_and_decrements_task_count() {
let manager = ScheduledTaskManager::new();
let task_id = manager.add_scheduled_task(
ScheduleMode::FixedRate,
Duration::from_secs(1),
Duration::from_secs(2),
|token| async move {
if token.is_cancelled() {
return Ok(());
}
Ok(())
},
);
manager.cancel_task(task_id);
assert_eq!(manager.task_count(), 0);
}
#[tokio::test]
async fn aborts_task_and_decrements_task_count() {
let manager = ScheduledTaskManager::new();
let task_id = manager.add_scheduled_task(
ScheduleMode::FixedRate,
Duration::from_secs(1),
Duration::from_secs(2),
|token| async move {
if token.is_cancelled() {
return Ok(());
}
Ok(())
},
);
manager.abort_task(task_id);
assert_eq!(manager.task_count(), 0);
}
#[tokio::test]
async fn cancels_all_tasks() {
let manager = ScheduledTaskManager::new();
for _ in 0..3 {
manager.add_scheduled_task(
ScheduleMode::FixedRate,
Duration::from_secs(1),
Duration::from_secs(2),
|token| async move {
if token.is_cancelled() {
return Ok(());
}
Ok(())
},
);
}
assert_eq!(manager.task_count(), 3);
manager.cancel_all();
assert_eq!(manager.task_count(), 0);
}
#[tokio::test]
async fn aborts_all_tasks() {
let manager = ScheduledTaskManager::new();
for _ in 0..3 {
manager.add_scheduled_task(
ScheduleMode::FixedRate,
Duration::from_secs(1),
Duration::from_secs(2),
|token| async move {
if token.is_cancelled() {
return Ok(());
}
Ok(())
},
);
}
assert_eq!(manager.task_count(), 3);
manager.abort_all();
assert_eq!(manager.task_count(), 0);
}
#[tokio::test]
async fn skips_task_execution_in_fixed_rate_no_overlap_mode() {
let manager = ScheduledTaskManager::new();
let task_id = manager.add_scheduled_task(
ScheduleMode::FixedRateNoOverlap,
Duration::from_secs(0),
Duration::from_millis(100),
|token| async move {
tokio::time::sleep(Duration::from_millis(200)).await;
if token.is_cancelled() {
return Ok(());
}
Ok(())
},
);
time::sleep(Duration::from_millis(400)).await;
manager.cancel_task(task_id);
assert_eq!(manager.task_count(), 0);
}
fn new_manager() -> ScheduledTaskManager {
ScheduledTaskManager::new()
}
#[tokio::test(flavor = "multi_thread", worker_threads = 2)]
async fn test_fixed_rate_task() {
let mgr = new_manager();
let counter = Arc::new(AtomicUsize::new(0));
let c = counter.clone();
let task_id = mgr.add_fixed_rate_task_async(
Duration::from_millis(50),
Duration::from_millis(100),
async move |_ctx| {
c.fetch_add(1, Ordering::Relaxed);
Ok(())
},
);
time::sleep(Duration::from_millis(500)).await;
mgr.cancel_task(task_id);
time::sleep(Duration::from_millis(50)).await;
let executed = counter.load(Ordering::Relaxed);
assert!(executed >= 3, "FixedRate executed too few times: {}", executed);
}
#[tokio::test(flavor = "multi_thread", worker_threads = 2)]
async fn test_fixed_delay_task() {
let mgr = new_manager();
let counter = Arc::new(AtomicUsize::new(0));
let c = counter.clone();
let task_id = mgr.add_fixed_delay_task_async(
Duration::from_millis(10),
Duration::from_millis(50),
async move |_ctx| {
c.fetch_add(1, Ordering::Relaxed);
Ok(())
},
);
time::sleep(Duration::from_millis(300)).await;
mgr.cancel_task(task_id);
time::sleep(Duration::from_millis(50)).await;
let executed = counter.load(Ordering::Relaxed);
assert!((3..=6).contains(&executed), "FixedDelay count unexpected: {}", executed);
}
#[tokio::test(flavor = "multi_thread", worker_threads = 2)]
async fn test_fixed_rate_no_overlap_task() {
let mgr = new_manager();
let counter = Arc::new(AtomicUsize::new(0));
let c = counter.clone();
let task_id = mgr.add_fixed_rate_no_overlap_task_async(
Duration::from_millis(10),
Duration::from_millis(50),
async move |_ctx| {
time::sleep(Duration::from_millis(80)).await;
c.fetch_add(1, Ordering::Relaxed);
Ok(())
},
);
time::sleep(Duration::from_millis(400)).await;
mgr.cancel_task(task_id);
time::sleep(Duration::from_millis(50)).await;
let executed = counter.load(Ordering::Relaxed);
assert!(
(2..=5).contains(&executed),
"FixedRateNoOverlap count unexpected: {}",
executed
);
}
}