Skip to main content

MiniTimer

Struct MiniTimer 

Source
pub struct MiniTimer { /* private fields */ }
Expand description

Main timer system for scheduling and executing tasks.

MiniTimer is the primary interface for users to interact with the timer system. It handles task scheduling, execution, and concurrency control.

Implementations§

Source§

impl MiniTimer

Source

pub fn new() -> Self

Creates a new MiniTimer instance.

§Returns

A new MiniTimer with initialized components.

Examples found in repository?
examples/once_delayed_task.rs (line 20)
19async fn main() {
20    let timer = minitimer::MiniTimer::new();
21
22    let task = TaskBuilder::new(1)
23        .with_frequency_once_by_seconds(3)
24        .spwan_async(DelayedPrintTask {
25            message: "Hello from minitimer!".to_string(),
26        })
27        .unwrap();
28
29    timer.add_task(task).unwrap();
30
31    println!("Timer started. Waiting 5 seconds...");
32    tokio::time::sleep(std::time::Duration::from_secs(5)).await;
33
34    println!("Example completed.");
35}
More examples
Hide additional examples
examples/repeated_task.rs (line 24)
21async fn main() {
22    let counter = std::sync::Arc::new(std::sync::Mutex::new(0));
23
24    let timer = minitimer::MiniTimer::new();
25
26    let task = TaskBuilder::new(1)
27        .with_frequency_repeated_by_seconds(1)
28        .spwan_async(PeriodicTask {
29            counter: counter.clone(),
30        })
31        .unwrap();
32
33    timer.add_task(task).unwrap();
34
35    println!("Timer started. Running periodic task every 1 second for 5 seconds...");
36    tokio::time::sleep(std::time::Duration::from_secs(5)).await;
37
38    let final_count = *counter.lock().unwrap();
39    println!("Example completed. Final count: {}", final_count);
40}
examples/countdown_task.rs (line 24)
21async fn main() {
22    let counter = std::sync::Arc::new(std::sync::Mutex::new(0));
23
24    let timer = minitimer::MiniTimer::new();
25
26    let task = TaskBuilder::new(1)
27        .with_frequency_count_down_by_seconds(3, 1)
28        .spwan_async(CountDownTask {
29            counter: counter.clone(),
30        })
31        .unwrap();
32
33    timer.add_task(task).unwrap();
34
35    println!("Timer started. Task will execute 3 times with 1 second interval...");
36    tokio::time::sleep(std::time::Duration::from_secs(5)).await;
37
38    let final_count = *counter.lock().unwrap();
39    println!("Example completed. Total executions: {}", final_count);
40}
examples/concurrency_control.rs (line 42)
38async fn main() {
39    let active_count = Arc::new(AtomicUsize::new(0));
40    let max_concurrency = 3;
41
42    let timer = minitimer::MiniTimer::new();
43
44    for i in 1..=5 {
45        let task = TaskBuilder::new(i)
46            .with_frequency_once_by_seconds(1)
47            .with_max_concurrency(max_concurrency)
48            .spwan_async(ConcurrentTask {
49                task_id: i,
50                active_count: active_count.clone(),
51            })
52            .unwrap();
53
54        timer.add_task(task).unwrap();
55    }
56
57    println!(
58        "Timer started. Added 5 tasks with max concurrency of {}. Waiting 3 seconds...",
59        max_concurrency
60    );
61    sleep(Duration::from_secs(3)).await;
62
63    println!("Example completed.");
64}
examples/task_management.rs (line 20)
19async fn main() {
20    let timer = minitimer::MiniTimer::new();
21
22    let task1 = TaskBuilder::new(1)
23        .with_frequency_repeated_by_seconds(2)
24        .spwan_async(SimpleTask { id: 1 })
25        .unwrap();
26
27    let task2 = TaskBuilder::new(2)
28        .with_frequency_once_by_seconds(5)
29        .spwan_async(SimpleTask { id: 2 })
30        .unwrap();
31
32    let task3 = TaskBuilder::new(3)
33        .with_frequency_count_down_by_seconds(3, 1)
34        .spwan_async(SimpleTask { id: 3 })
35        .unwrap();
36
37    timer.add_task(task1).unwrap();
38    timer.add_task(task2).unwrap();
39    timer.add_task(task3).unwrap();
40
41    println!("Added 3 tasks. Initial task count: {}", timer.task_count());
42
43    println!("\n--- Pending tasks: {:?}", timer.get_pending_tasks());
44    println!("--- Running tasks: {:?}", timer.get_running_tasks());
45
46    if let Some(status) = timer.task_status(1) {
47        println!("\nTask 1 status: {:?}", status);
48    }
49
50    println!("\n--- Removing task 2 ---");
51    let removed = timer.remove_task(2);
52    if removed.is_some() {
53        println!("Task 2 removed successfully!");
54    }
55
56    println!("Task count after removal: {}", timer.task_count());
57    println!("Contains task 1: {}", timer.contains_task(1));
58    println!("Contains task 2: {}", timer.contains_task(2));
59
60    println!("\nWaiting 4 seconds to let tasks run...");
61    tokio::time::sleep(std::time::Duration::from_secs(4)).await;
62
63    println!("\n--- After 4 seconds ---");
64    println!("Task 1 status: {:?}", timer.task_status(1));
65    println!("Task 3 status: {:?}", timer.task_status(3));
66    println!("Running tasks: {:?}", timer.get_running_tasks());
67
68    println!("\nExample completed.");
69}
examples/advance_task.rs (line 26)
24async fn main() {
25    let counter = Arc::new(AtomicU64::new(0));
26    let timer = minitimer::MiniTimer::new();
27
28    let task = TaskBuilder::new(1)
29        .with_frequency_repeated_by_seconds(60)
30        .spwan_async(CounterTask {
31            id: 1,
32            counter: counter.clone(),
33        })
34        .unwrap();
35
36    timer.add_task(task).unwrap();
37
38    println!("Task 1 added with 60-second interval.");
39    println!("Initial task count: {}", timer.task_count());
40
41    println!("\n--- Test 1: Advance task by 30 seconds ---");
42    println!("Task was scheduled for 60 seconds from now.");
43    println!("Advancing by 30 seconds...");
44
45    timer
46        .advance_task(1, Some(Duration::from_secs(30)), true)
47        .unwrap();
48
49    println!(
50        "Task 1 still exists after advance: {}",
51        timer.contains_task(1)
52    );
53
54    println!("\n--- Test 2: Trigger task immediately ---");
55    println!("Triggering task 1 immediately (None duration)...");
56
57    timer.advance_task(1, None, true).unwrap();
58
59    println!(
60        "Task 1 still exists after trigger: {}",
61        timer.contains_task(1)
62    );
63
64    println!("\n--- Test 3: Advance beyond wait time ---");
65    let task2 = TaskBuilder::new(2)
66        .with_frequency_repeated_by_seconds(60)
67        .spwan_async(CounterTask {
68            id: 2,
69            counter: counter.clone(),
70        })
71        .unwrap();
72
73    timer.add_task(task2).unwrap();
74
75    println!("Task 2 scheduled for 60 seconds, advancing by 120 seconds (beyond wait)...");
76
77    timer
78        .advance_task(2, Some(Duration::from_secs(120)), true)
79        .unwrap();
80
81    println!("Task 2 still exists: {}", timer.contains_task(2));
82
83    println!("\n--- Test 4: Advance non-existent task (error case) ---");
84
85    let result = timer.advance_task(999, Some(Duration::from_secs(30)), true);
86
87    match result {
88        Ok(_) => println!("Unexpected success!"),
89        Err(e) => println!("Expected error: {}", e),
90    }
91
92    println!("\n--- Final task count: {} ---", timer.task_count());
93
94    println!("\nExample completed. The advance_task API allows:");
95    println!("  - advance_task(id, None)        -> Trigger immediately, schedule next run");
96    println!("  - advance_task(id, Some(duration)) -> Advance by specific duration");
97    println!("  - If duration > remaining wait, triggers immediately and schedules next run");
98    println!("\nNote: For repeating tasks, after acceleration the frequency sequence");
99    println!("is reset from the current time, ensuring consistent intervals for");
100    println!("subsequent executions.");
101
102    timer.stop().await;
103}
Source

pub async fn tick(&self)

Advances the timer by one tick (one second).

This is useful for testing purposes to simulate time progression without waiting for the real clock. Note: This requires start() to be called first to start the event loop.

Source

pub fn add_task(&self, task: Task) -> Result<(), TaskError>

Adds a task to the timer system.

§Arguments
  • task - The task to add
§Returns
  • Ok(()) - If the task was successfully added
  • Err(TaskError) - If there was an error adding the task
Examples found in repository?
examples/once_delayed_task.rs (line 29)
19async fn main() {
20    let timer = minitimer::MiniTimer::new();
21
22    let task = TaskBuilder::new(1)
23        .with_frequency_once_by_seconds(3)
24        .spwan_async(DelayedPrintTask {
25            message: "Hello from minitimer!".to_string(),
26        })
27        .unwrap();
28
29    timer.add_task(task).unwrap();
30
31    println!("Timer started. Waiting 5 seconds...");
32    tokio::time::sleep(std::time::Duration::from_secs(5)).await;
33
34    println!("Example completed.");
35}
More examples
Hide additional examples
examples/repeated_task.rs (line 33)
21async fn main() {
22    let counter = std::sync::Arc::new(std::sync::Mutex::new(0));
23
24    let timer = minitimer::MiniTimer::new();
25
26    let task = TaskBuilder::new(1)
27        .with_frequency_repeated_by_seconds(1)
28        .spwan_async(PeriodicTask {
29            counter: counter.clone(),
30        })
31        .unwrap();
32
33    timer.add_task(task).unwrap();
34
35    println!("Timer started. Running periodic task every 1 second for 5 seconds...");
36    tokio::time::sleep(std::time::Duration::from_secs(5)).await;
37
38    let final_count = *counter.lock().unwrap();
39    println!("Example completed. Final count: {}", final_count);
40}
examples/countdown_task.rs (line 33)
21async fn main() {
22    let counter = std::sync::Arc::new(std::sync::Mutex::new(0));
23
24    let timer = minitimer::MiniTimer::new();
25
26    let task = TaskBuilder::new(1)
27        .with_frequency_count_down_by_seconds(3, 1)
28        .spwan_async(CountDownTask {
29            counter: counter.clone(),
30        })
31        .unwrap();
32
33    timer.add_task(task).unwrap();
34
35    println!("Timer started. Task will execute 3 times with 1 second interval...");
36    tokio::time::sleep(std::time::Duration::from_secs(5)).await;
37
38    let final_count = *counter.lock().unwrap();
39    println!("Example completed. Total executions: {}", final_count);
40}
examples/concurrency_control.rs (line 54)
38async fn main() {
39    let active_count = Arc::new(AtomicUsize::new(0));
40    let max_concurrency = 3;
41
42    let timer = minitimer::MiniTimer::new();
43
44    for i in 1..=5 {
45        let task = TaskBuilder::new(i)
46            .with_frequency_once_by_seconds(1)
47            .with_max_concurrency(max_concurrency)
48            .spwan_async(ConcurrentTask {
49                task_id: i,
50                active_count: active_count.clone(),
51            })
52            .unwrap();
53
54        timer.add_task(task).unwrap();
55    }
56
57    println!(
58        "Timer started. Added 5 tasks with max concurrency of {}. Waiting 3 seconds...",
59        max_concurrency
60    );
61    sleep(Duration::from_secs(3)).await;
62
63    println!("Example completed.");
64}
examples/task_management.rs (line 37)
19async fn main() {
20    let timer = minitimer::MiniTimer::new();
21
22    let task1 = TaskBuilder::new(1)
23        .with_frequency_repeated_by_seconds(2)
24        .spwan_async(SimpleTask { id: 1 })
25        .unwrap();
26
27    let task2 = TaskBuilder::new(2)
28        .with_frequency_once_by_seconds(5)
29        .spwan_async(SimpleTask { id: 2 })
30        .unwrap();
31
32    let task3 = TaskBuilder::new(3)
33        .with_frequency_count_down_by_seconds(3, 1)
34        .spwan_async(SimpleTask { id: 3 })
35        .unwrap();
36
37    timer.add_task(task1).unwrap();
38    timer.add_task(task2).unwrap();
39    timer.add_task(task3).unwrap();
40
41    println!("Added 3 tasks. Initial task count: {}", timer.task_count());
42
43    println!("\n--- Pending tasks: {:?}", timer.get_pending_tasks());
44    println!("--- Running tasks: {:?}", timer.get_running_tasks());
45
46    if let Some(status) = timer.task_status(1) {
47        println!("\nTask 1 status: {:?}", status);
48    }
49
50    println!("\n--- Removing task 2 ---");
51    let removed = timer.remove_task(2);
52    if removed.is_some() {
53        println!("Task 2 removed successfully!");
54    }
55
56    println!("Task count after removal: {}", timer.task_count());
57    println!("Contains task 1: {}", timer.contains_task(1));
58    println!("Contains task 2: {}", timer.contains_task(2));
59
60    println!("\nWaiting 4 seconds to let tasks run...");
61    tokio::time::sleep(std::time::Duration::from_secs(4)).await;
62
63    println!("\n--- After 4 seconds ---");
64    println!("Task 1 status: {:?}", timer.task_status(1));
65    println!("Task 3 status: {:?}", timer.task_status(3));
66    println!("Running tasks: {:?}", timer.get_running_tasks());
67
68    println!("\nExample completed.");
69}
examples/advance_task.rs (line 36)
24async fn main() {
25    let counter = Arc::new(AtomicU64::new(0));
26    let timer = minitimer::MiniTimer::new();
27
28    let task = TaskBuilder::new(1)
29        .with_frequency_repeated_by_seconds(60)
30        .spwan_async(CounterTask {
31            id: 1,
32            counter: counter.clone(),
33        })
34        .unwrap();
35
36    timer.add_task(task).unwrap();
37
38    println!("Task 1 added with 60-second interval.");
39    println!("Initial task count: {}", timer.task_count());
40
41    println!("\n--- Test 1: Advance task by 30 seconds ---");
42    println!("Task was scheduled for 60 seconds from now.");
43    println!("Advancing by 30 seconds...");
44
45    timer
46        .advance_task(1, Some(Duration::from_secs(30)), true)
47        .unwrap();
48
49    println!(
50        "Task 1 still exists after advance: {}",
51        timer.contains_task(1)
52    );
53
54    println!("\n--- Test 2: Trigger task immediately ---");
55    println!("Triggering task 1 immediately (None duration)...");
56
57    timer.advance_task(1, None, true).unwrap();
58
59    println!(
60        "Task 1 still exists after trigger: {}",
61        timer.contains_task(1)
62    );
63
64    println!("\n--- Test 3: Advance beyond wait time ---");
65    let task2 = TaskBuilder::new(2)
66        .with_frequency_repeated_by_seconds(60)
67        .spwan_async(CounterTask {
68            id: 2,
69            counter: counter.clone(),
70        })
71        .unwrap();
72
73    timer.add_task(task2).unwrap();
74
75    println!("Task 2 scheduled for 60 seconds, advancing by 120 seconds (beyond wait)...");
76
77    timer
78        .advance_task(2, Some(Duration::from_secs(120)), true)
79        .unwrap();
80
81    println!("Task 2 still exists: {}", timer.contains_task(2));
82
83    println!("\n--- Test 4: Advance non-existent task (error case) ---");
84
85    let result = timer.advance_task(999, Some(Duration::from_secs(30)), true);
86
87    match result {
88        Ok(_) => println!("Unexpected success!"),
89        Err(e) => println!("Expected error: {}", e),
90    }
91
92    println!("\n--- Final task count: {} ---", timer.task_count());
93
94    println!("\nExample completed. The advance_task API allows:");
95    println!("  - advance_task(id, None)        -> Trigger immediately, schedule next run");
96    println!("  - advance_task(id, Some(duration)) -> Advance by specific duration");
97    println!("  - If duration > remaining wait, triggers immediately and schedules next run");
98    println!("\nNote: For repeating tasks, after acceleration the frequency sequence");
99    println!("is reset from the current time, ensuring consistent intervals for");
100    println!("subsequent executions.");
101
102    timer.stop().await;
103}
Source

pub fn remove_task(&self, task_id: TaskId) -> Option<Task>

Removes a task from the timer system.

§Arguments
  • task_id - The ID of the task to remove
§Returns

The removed task if it existed, None otherwise.

Examples found in repository?
examples/task_management.rs (line 51)
19async fn main() {
20    let timer = minitimer::MiniTimer::new();
21
22    let task1 = TaskBuilder::new(1)
23        .with_frequency_repeated_by_seconds(2)
24        .spwan_async(SimpleTask { id: 1 })
25        .unwrap();
26
27    let task2 = TaskBuilder::new(2)
28        .with_frequency_once_by_seconds(5)
29        .spwan_async(SimpleTask { id: 2 })
30        .unwrap();
31
32    let task3 = TaskBuilder::new(3)
33        .with_frequency_count_down_by_seconds(3, 1)
34        .spwan_async(SimpleTask { id: 3 })
35        .unwrap();
36
37    timer.add_task(task1).unwrap();
38    timer.add_task(task2).unwrap();
39    timer.add_task(task3).unwrap();
40
41    println!("Added 3 tasks. Initial task count: {}", timer.task_count());
42
43    println!("\n--- Pending tasks: {:?}", timer.get_pending_tasks());
44    println!("--- Running tasks: {:?}", timer.get_running_tasks());
45
46    if let Some(status) = timer.task_status(1) {
47        println!("\nTask 1 status: {:?}", status);
48    }
49
50    println!("\n--- Removing task 2 ---");
51    let removed = timer.remove_task(2);
52    if removed.is_some() {
53        println!("Task 2 removed successfully!");
54    }
55
56    println!("Task count after removal: {}", timer.task_count());
57    println!("Contains task 1: {}", timer.contains_task(1));
58    println!("Contains task 2: {}", timer.contains_task(2));
59
60    println!("\nWaiting 4 seconds to let tasks run...");
61    tokio::time::sleep(std::time::Duration::from_secs(4)).await;
62
63    println!("\n--- After 4 seconds ---");
64    println!("Task 1 status: {:?}", timer.task_status(1));
65    println!("Task 3 status: {:?}", timer.task_status(3));
66    println!("Running tasks: {:?}", timer.get_running_tasks());
67
68    println!("\nExample completed.");
69}
Source

pub fn contains_task(&self, task_id: TaskId) -> bool

Checks if a task exists in the timer system.

§Arguments
  • task_id - The ID of the task to check
§Returns

true if the task exists, false otherwise.

Examples found in repository?
examples/task_management.rs (line 57)
19async fn main() {
20    let timer = minitimer::MiniTimer::new();
21
22    let task1 = TaskBuilder::new(1)
23        .with_frequency_repeated_by_seconds(2)
24        .spwan_async(SimpleTask { id: 1 })
25        .unwrap();
26
27    let task2 = TaskBuilder::new(2)
28        .with_frequency_once_by_seconds(5)
29        .spwan_async(SimpleTask { id: 2 })
30        .unwrap();
31
32    let task3 = TaskBuilder::new(3)
33        .with_frequency_count_down_by_seconds(3, 1)
34        .spwan_async(SimpleTask { id: 3 })
35        .unwrap();
36
37    timer.add_task(task1).unwrap();
38    timer.add_task(task2).unwrap();
39    timer.add_task(task3).unwrap();
40
41    println!("Added 3 tasks. Initial task count: {}", timer.task_count());
42
43    println!("\n--- Pending tasks: {:?}", timer.get_pending_tasks());
44    println!("--- Running tasks: {:?}", timer.get_running_tasks());
45
46    if let Some(status) = timer.task_status(1) {
47        println!("\nTask 1 status: {:?}", status);
48    }
49
50    println!("\n--- Removing task 2 ---");
51    let removed = timer.remove_task(2);
52    if removed.is_some() {
53        println!("Task 2 removed successfully!");
54    }
55
56    println!("Task count after removal: {}", timer.task_count());
57    println!("Contains task 1: {}", timer.contains_task(1));
58    println!("Contains task 2: {}", timer.contains_task(2));
59
60    println!("\nWaiting 4 seconds to let tasks run...");
61    tokio::time::sleep(std::time::Duration::from_secs(4)).await;
62
63    println!("\n--- After 4 seconds ---");
64    println!("Task 1 status: {:?}", timer.task_status(1));
65    println!("Task 3 status: {:?}", timer.task_status(3));
66    println!("Running tasks: {:?}", timer.get_running_tasks());
67
68    println!("\nExample completed.");
69}
More examples
Hide additional examples
examples/advance_task.rs (line 51)
24async fn main() {
25    let counter = Arc::new(AtomicU64::new(0));
26    let timer = minitimer::MiniTimer::new();
27
28    let task = TaskBuilder::new(1)
29        .with_frequency_repeated_by_seconds(60)
30        .spwan_async(CounterTask {
31            id: 1,
32            counter: counter.clone(),
33        })
34        .unwrap();
35
36    timer.add_task(task).unwrap();
37
38    println!("Task 1 added with 60-second interval.");
39    println!("Initial task count: {}", timer.task_count());
40
41    println!("\n--- Test 1: Advance task by 30 seconds ---");
42    println!("Task was scheduled for 60 seconds from now.");
43    println!("Advancing by 30 seconds...");
44
45    timer
46        .advance_task(1, Some(Duration::from_secs(30)), true)
47        .unwrap();
48
49    println!(
50        "Task 1 still exists after advance: {}",
51        timer.contains_task(1)
52    );
53
54    println!("\n--- Test 2: Trigger task immediately ---");
55    println!("Triggering task 1 immediately (None duration)...");
56
57    timer.advance_task(1, None, true).unwrap();
58
59    println!(
60        "Task 1 still exists after trigger: {}",
61        timer.contains_task(1)
62    );
63
64    println!("\n--- Test 3: Advance beyond wait time ---");
65    let task2 = TaskBuilder::new(2)
66        .with_frequency_repeated_by_seconds(60)
67        .spwan_async(CounterTask {
68            id: 2,
69            counter: counter.clone(),
70        })
71        .unwrap();
72
73    timer.add_task(task2).unwrap();
74
75    println!("Task 2 scheduled for 60 seconds, advancing by 120 seconds (beyond wait)...");
76
77    timer
78        .advance_task(2, Some(Duration::from_secs(120)), true)
79        .unwrap();
80
81    println!("Task 2 still exists: {}", timer.contains_task(2));
82
83    println!("\n--- Test 4: Advance non-existent task (error case) ---");
84
85    let result = timer.advance_task(999, Some(Duration::from_secs(30)), true);
86
87    match result {
88        Ok(_) => println!("Unexpected success!"),
89        Err(e) => println!("Expected error: {}", e),
90    }
91
92    println!("\n--- Final task count: {} ---", timer.task_count());
93
94    println!("\nExample completed. The advance_task API allows:");
95    println!("  - advance_task(id, None)        -> Trigger immediately, schedule next run");
96    println!("  - advance_task(id, Some(duration)) -> Advance by specific duration");
97    println!("  - If duration > remaining wait, triggers immediately and schedules next run");
98    println!("\nNote: For repeating tasks, after acceleration the frequency sequence");
99    println!("is reset from the current time, ensuring consistent intervals for");
100    println!("subsequent executions.");
101
102    timer.stop().await;
103}
Source

pub fn task_count(&self) -> usize

Gets the total number of tasks in the timer system.

§Returns

The number of tasks currently scheduled.

Examples found in repository?
examples/task_management.rs (line 41)
19async fn main() {
20    let timer = minitimer::MiniTimer::new();
21
22    let task1 = TaskBuilder::new(1)
23        .with_frequency_repeated_by_seconds(2)
24        .spwan_async(SimpleTask { id: 1 })
25        .unwrap();
26
27    let task2 = TaskBuilder::new(2)
28        .with_frequency_once_by_seconds(5)
29        .spwan_async(SimpleTask { id: 2 })
30        .unwrap();
31
32    let task3 = TaskBuilder::new(3)
33        .with_frequency_count_down_by_seconds(3, 1)
34        .spwan_async(SimpleTask { id: 3 })
35        .unwrap();
36
37    timer.add_task(task1).unwrap();
38    timer.add_task(task2).unwrap();
39    timer.add_task(task3).unwrap();
40
41    println!("Added 3 tasks. Initial task count: {}", timer.task_count());
42
43    println!("\n--- Pending tasks: {:?}", timer.get_pending_tasks());
44    println!("--- Running tasks: {:?}", timer.get_running_tasks());
45
46    if let Some(status) = timer.task_status(1) {
47        println!("\nTask 1 status: {:?}", status);
48    }
49
50    println!("\n--- Removing task 2 ---");
51    let removed = timer.remove_task(2);
52    if removed.is_some() {
53        println!("Task 2 removed successfully!");
54    }
55
56    println!("Task count after removal: {}", timer.task_count());
57    println!("Contains task 1: {}", timer.contains_task(1));
58    println!("Contains task 2: {}", timer.contains_task(2));
59
60    println!("\nWaiting 4 seconds to let tasks run...");
61    tokio::time::sleep(std::time::Duration::from_secs(4)).await;
62
63    println!("\n--- After 4 seconds ---");
64    println!("Task 1 status: {:?}", timer.task_status(1));
65    println!("Task 3 status: {:?}", timer.task_status(3));
66    println!("Running tasks: {:?}", timer.get_running_tasks());
67
68    println!("\nExample completed.");
69}
More examples
Hide additional examples
examples/advance_task.rs (line 39)
24async fn main() {
25    let counter = Arc::new(AtomicU64::new(0));
26    let timer = minitimer::MiniTimer::new();
27
28    let task = TaskBuilder::new(1)
29        .with_frequency_repeated_by_seconds(60)
30        .spwan_async(CounterTask {
31            id: 1,
32            counter: counter.clone(),
33        })
34        .unwrap();
35
36    timer.add_task(task).unwrap();
37
38    println!("Task 1 added with 60-second interval.");
39    println!("Initial task count: {}", timer.task_count());
40
41    println!("\n--- Test 1: Advance task by 30 seconds ---");
42    println!("Task was scheduled for 60 seconds from now.");
43    println!("Advancing by 30 seconds...");
44
45    timer
46        .advance_task(1, Some(Duration::from_secs(30)), true)
47        .unwrap();
48
49    println!(
50        "Task 1 still exists after advance: {}",
51        timer.contains_task(1)
52    );
53
54    println!("\n--- Test 2: Trigger task immediately ---");
55    println!("Triggering task 1 immediately (None duration)...");
56
57    timer.advance_task(1, None, true).unwrap();
58
59    println!(
60        "Task 1 still exists after trigger: {}",
61        timer.contains_task(1)
62    );
63
64    println!("\n--- Test 3: Advance beyond wait time ---");
65    let task2 = TaskBuilder::new(2)
66        .with_frequency_repeated_by_seconds(60)
67        .spwan_async(CounterTask {
68            id: 2,
69            counter: counter.clone(),
70        })
71        .unwrap();
72
73    timer.add_task(task2).unwrap();
74
75    println!("Task 2 scheduled for 60 seconds, advancing by 120 seconds (beyond wait)...");
76
77    timer
78        .advance_task(2, Some(Duration::from_secs(120)), true)
79        .unwrap();
80
81    println!("Task 2 still exists: {}", timer.contains_task(2));
82
83    println!("\n--- Test 4: Advance non-existent task (error case) ---");
84
85    let result = timer.advance_task(999, Some(Duration::from_secs(30)), true);
86
87    match result {
88        Ok(_) => println!("Unexpected success!"),
89        Err(e) => println!("Expected error: {}", e),
90    }
91
92    println!("\n--- Final task count: {} ---", timer.task_count());
93
94    println!("\nExample completed. The advance_task API allows:");
95    println!("  - advance_task(id, None)        -> Trigger immediately, schedule next run");
96    println!("  - advance_task(id, Some(duration)) -> Advance by specific duration");
97    println!("  - If duration > remaining wait, triggers immediately and schedules next run");
98    println!("\nNote: For repeating tasks, after acceleration the frequency sequence");
99    println!("is reset from the current time, ensuring consistent intervals for");
100    println!("subsequent executions.");
101
102    timer.stop().await;
103}
Source

pub fn get_pending_tasks(&self) -> Vec<TaskId>

Gets a list of all pending tasks.

§Returns

A vector of task IDs that are currently pending execution.

Examples found in repository?
examples/task_management.rs (line 43)
19async fn main() {
20    let timer = minitimer::MiniTimer::new();
21
22    let task1 = TaskBuilder::new(1)
23        .with_frequency_repeated_by_seconds(2)
24        .spwan_async(SimpleTask { id: 1 })
25        .unwrap();
26
27    let task2 = TaskBuilder::new(2)
28        .with_frequency_once_by_seconds(5)
29        .spwan_async(SimpleTask { id: 2 })
30        .unwrap();
31
32    let task3 = TaskBuilder::new(3)
33        .with_frequency_count_down_by_seconds(3, 1)
34        .spwan_async(SimpleTask { id: 3 })
35        .unwrap();
36
37    timer.add_task(task1).unwrap();
38    timer.add_task(task2).unwrap();
39    timer.add_task(task3).unwrap();
40
41    println!("Added 3 tasks. Initial task count: {}", timer.task_count());
42
43    println!("\n--- Pending tasks: {:?}", timer.get_pending_tasks());
44    println!("--- Running tasks: {:?}", timer.get_running_tasks());
45
46    if let Some(status) = timer.task_status(1) {
47        println!("\nTask 1 status: {:?}", status);
48    }
49
50    println!("\n--- Removing task 2 ---");
51    let removed = timer.remove_task(2);
52    if removed.is_some() {
53        println!("Task 2 removed successfully!");
54    }
55
56    println!("Task count after removal: {}", timer.task_count());
57    println!("Contains task 1: {}", timer.contains_task(1));
58    println!("Contains task 2: {}", timer.contains_task(2));
59
60    println!("\nWaiting 4 seconds to let tasks run...");
61    tokio::time::sleep(std::time::Duration::from_secs(4)).await;
62
63    println!("\n--- After 4 seconds ---");
64    println!("Task 1 status: {:?}", timer.task_status(1));
65    println!("Task 3 status: {:?}", timer.task_status(3));
66    println!("Running tasks: {:?}", timer.get_running_tasks());
67
68    println!("\nExample completed.");
69}
Source

pub fn get_running_tasks(&self) -> Vec<TaskId>

Gets a list of all running tasks.

§Returns

A vector of task IDs that are currently running.

Examples found in repository?
examples/task_management.rs (line 44)
19async fn main() {
20    let timer = minitimer::MiniTimer::new();
21
22    let task1 = TaskBuilder::new(1)
23        .with_frequency_repeated_by_seconds(2)
24        .spwan_async(SimpleTask { id: 1 })
25        .unwrap();
26
27    let task2 = TaskBuilder::new(2)
28        .with_frequency_once_by_seconds(5)
29        .spwan_async(SimpleTask { id: 2 })
30        .unwrap();
31
32    let task3 = TaskBuilder::new(3)
33        .with_frequency_count_down_by_seconds(3, 1)
34        .spwan_async(SimpleTask { id: 3 })
35        .unwrap();
36
37    timer.add_task(task1).unwrap();
38    timer.add_task(task2).unwrap();
39    timer.add_task(task3).unwrap();
40
41    println!("Added 3 tasks. Initial task count: {}", timer.task_count());
42
43    println!("\n--- Pending tasks: {:?}", timer.get_pending_tasks());
44    println!("--- Running tasks: {:?}", timer.get_running_tasks());
45
46    if let Some(status) = timer.task_status(1) {
47        println!("\nTask 1 status: {:?}", status);
48    }
49
50    println!("\n--- Removing task 2 ---");
51    let removed = timer.remove_task(2);
52    if removed.is_some() {
53        println!("Task 2 removed successfully!");
54    }
55
56    println!("Task count after removal: {}", timer.task_count());
57    println!("Contains task 1: {}", timer.contains_task(1));
58    println!("Contains task 2: {}", timer.contains_task(2));
59
60    println!("\nWaiting 4 seconds to let tasks run...");
61    tokio::time::sleep(std::time::Duration::from_secs(4)).await;
62
63    println!("\n--- After 4 seconds ---");
64    println!("Task 1 status: {:?}", timer.task_status(1));
65    println!("Task 3 status: {:?}", timer.task_status(3));
66    println!("Running tasks: {:?}", timer.get_running_tasks());
67
68    println!("\nExample completed.");
69}
Source

pub fn task_status(&self, task_id: TaskId) -> Option<TaskStatus>

Gets the current status of a task.

§Arguments
  • task_id - The ID of the task to check
§Returns
  • Some(TaskStatus) - If the task exists, containing all tracking information
  • None - If the task doesn’t exist
Examples found in repository?
examples/task_management.rs (line 46)
19async fn main() {
20    let timer = minitimer::MiniTimer::new();
21
22    let task1 = TaskBuilder::new(1)
23        .with_frequency_repeated_by_seconds(2)
24        .spwan_async(SimpleTask { id: 1 })
25        .unwrap();
26
27    let task2 = TaskBuilder::new(2)
28        .with_frequency_once_by_seconds(5)
29        .spwan_async(SimpleTask { id: 2 })
30        .unwrap();
31
32    let task3 = TaskBuilder::new(3)
33        .with_frequency_count_down_by_seconds(3, 1)
34        .spwan_async(SimpleTask { id: 3 })
35        .unwrap();
36
37    timer.add_task(task1).unwrap();
38    timer.add_task(task2).unwrap();
39    timer.add_task(task3).unwrap();
40
41    println!("Added 3 tasks. Initial task count: {}", timer.task_count());
42
43    println!("\n--- Pending tasks: {:?}", timer.get_pending_tasks());
44    println!("--- Running tasks: {:?}", timer.get_running_tasks());
45
46    if let Some(status) = timer.task_status(1) {
47        println!("\nTask 1 status: {:?}", status);
48    }
49
50    println!("\n--- Removing task 2 ---");
51    let removed = timer.remove_task(2);
52    if removed.is_some() {
53        println!("Task 2 removed successfully!");
54    }
55
56    println!("Task count after removal: {}", timer.task_count());
57    println!("Contains task 1: {}", timer.contains_task(1));
58    println!("Contains task 2: {}", timer.contains_task(2));
59
60    println!("\nWaiting 4 seconds to let tasks run...");
61    tokio::time::sleep(std::time::Duration::from_secs(4)).await;
62
63    println!("\n--- After 4 seconds ---");
64    println!("Task 1 status: {:?}", timer.task_status(1));
65    println!("Task 3 status: {:?}", timer.task_status(3));
66    println!("Running tasks: {:?}", timer.get_running_tasks());
67
68    println!("\nExample completed.");
69}
Source

pub fn advance_task( &self, task_id: TaskId, duration: Option<Duration>, reset_frequency: bool, ) -> Result<(), TaskError>

Advances a task’s scheduled execution time.

  • If duration is None: triggers the task immediately and schedules the next run
  • If duration is Some(duration): advances the task by the specified duration

For repeating tasks, the reset_frequency parameter controls whether to reset the frequency sequence from the current time:

  • If true (default): resets the frequency sequence, ensuring consistent intervals
  • If false: preserves the current frequency sequence position
§Arguments
  • task_id - The ID of the task to advance
  • duration - Optional duration to advance by. None means trigger immediately.
  • reset_frequency - Whether to reset the frequency sequence for repeating tasks (default: true)
§Returns
  • Ok(()) - If the task was successfully advanced
  • Err(TaskError) - If the task doesn’t exist
Examples found in repository?
examples/advance_task.rs (line 46)
24async fn main() {
25    let counter = Arc::new(AtomicU64::new(0));
26    let timer = minitimer::MiniTimer::new();
27
28    let task = TaskBuilder::new(1)
29        .with_frequency_repeated_by_seconds(60)
30        .spwan_async(CounterTask {
31            id: 1,
32            counter: counter.clone(),
33        })
34        .unwrap();
35
36    timer.add_task(task).unwrap();
37
38    println!("Task 1 added with 60-second interval.");
39    println!("Initial task count: {}", timer.task_count());
40
41    println!("\n--- Test 1: Advance task by 30 seconds ---");
42    println!("Task was scheduled for 60 seconds from now.");
43    println!("Advancing by 30 seconds...");
44
45    timer
46        .advance_task(1, Some(Duration::from_secs(30)), true)
47        .unwrap();
48
49    println!(
50        "Task 1 still exists after advance: {}",
51        timer.contains_task(1)
52    );
53
54    println!("\n--- Test 2: Trigger task immediately ---");
55    println!("Triggering task 1 immediately (None duration)...");
56
57    timer.advance_task(1, None, true).unwrap();
58
59    println!(
60        "Task 1 still exists after trigger: {}",
61        timer.contains_task(1)
62    );
63
64    println!("\n--- Test 3: Advance beyond wait time ---");
65    let task2 = TaskBuilder::new(2)
66        .with_frequency_repeated_by_seconds(60)
67        .spwan_async(CounterTask {
68            id: 2,
69            counter: counter.clone(),
70        })
71        .unwrap();
72
73    timer.add_task(task2).unwrap();
74
75    println!("Task 2 scheduled for 60 seconds, advancing by 120 seconds (beyond wait)...");
76
77    timer
78        .advance_task(2, Some(Duration::from_secs(120)), true)
79        .unwrap();
80
81    println!("Task 2 still exists: {}", timer.contains_task(2));
82
83    println!("\n--- Test 4: Advance non-existent task (error case) ---");
84
85    let result = timer.advance_task(999, Some(Duration::from_secs(30)), true);
86
87    match result {
88        Ok(_) => println!("Unexpected success!"),
89        Err(e) => println!("Expected error: {}", e),
90    }
91
92    println!("\n--- Final task count: {} ---", timer.task_count());
93
94    println!("\nExample completed. The advance_task API allows:");
95    println!("  - advance_task(id, None)        -> Trigger immediately, schedule next run");
96    println!("  - advance_task(id, Some(duration)) -> Advance by specific duration");
97    println!("  - If duration > remaining wait, triggers immediately and schedules next run");
98    println!("\nNote: For repeating tasks, after acceleration the frequency sequence");
99    println!("is reset from the current time, ensuring consistent intervals for");
100    println!("subsequent executions.");
101
102    timer.stop().await;
103}
Source

pub async fn stop(&self)

Stops the timer system.

This stops the internal timer and sets the running flag to false.

Examples found in repository?
examples/advance_task.rs (line 102)
24async fn main() {
25    let counter = Arc::new(AtomicU64::new(0));
26    let timer = minitimer::MiniTimer::new();
27
28    let task = TaskBuilder::new(1)
29        .with_frequency_repeated_by_seconds(60)
30        .spwan_async(CounterTask {
31            id: 1,
32            counter: counter.clone(),
33        })
34        .unwrap();
35
36    timer.add_task(task).unwrap();
37
38    println!("Task 1 added with 60-second interval.");
39    println!("Initial task count: {}", timer.task_count());
40
41    println!("\n--- Test 1: Advance task by 30 seconds ---");
42    println!("Task was scheduled for 60 seconds from now.");
43    println!("Advancing by 30 seconds...");
44
45    timer
46        .advance_task(1, Some(Duration::from_secs(30)), true)
47        .unwrap();
48
49    println!(
50        "Task 1 still exists after advance: {}",
51        timer.contains_task(1)
52    );
53
54    println!("\n--- Test 2: Trigger task immediately ---");
55    println!("Triggering task 1 immediately (None duration)...");
56
57    timer.advance_task(1, None, true).unwrap();
58
59    println!(
60        "Task 1 still exists after trigger: {}",
61        timer.contains_task(1)
62    );
63
64    println!("\n--- Test 3: Advance beyond wait time ---");
65    let task2 = TaskBuilder::new(2)
66        .with_frequency_repeated_by_seconds(60)
67        .spwan_async(CounterTask {
68            id: 2,
69            counter: counter.clone(),
70        })
71        .unwrap();
72
73    timer.add_task(task2).unwrap();
74
75    println!("Task 2 scheduled for 60 seconds, advancing by 120 seconds (beyond wait)...");
76
77    timer
78        .advance_task(2, Some(Duration::from_secs(120)), true)
79        .unwrap();
80
81    println!("Task 2 still exists: {}", timer.contains_task(2));
82
83    println!("\n--- Test 4: Advance non-existent task (error case) ---");
84
85    let result = timer.advance_task(999, Some(Duration::from_secs(30)), true);
86
87    match result {
88        Ok(_) => println!("Unexpected success!"),
89        Err(e) => println!("Expected error: {}", e),
90    }
91
92    println!("\n--- Final task count: {} ---", timer.task_count());
93
94    println!("\nExample completed. The advance_task API allows:");
95    println!("  - advance_task(id, None)        -> Trigger immediately, schedule next run");
96    println!("  - advance_task(id, Some(duration)) -> Advance by specific duration");
97    println!("  - If duration > remaining wait, triggers immediately and schedules next run");
98    println!("\nNote: For repeating tasks, after acceleration the frequency sequence");
99    println!("is reset from the current time, ensuring consistent intervals for");
100    println!("subsequent executions.");
101
102    timer.stop().await;
103}
Source

pub fn is_running(&self) -> bool

Checks if the timer system is currently running.

§Returns

true if the timer is running, false otherwise.

Trait Implementations§

Source§

impl Clone for MiniTimer

Source§

fn clone(&self) -> Self

Returns a duplicate of the value. Read more
1.0.0 · Source§

fn clone_from(&mut self, source: &Self)

Performs copy-assignment from source. Read more
Source§

impl Default for MiniTimer

Source§

fn default() -> Self

Returns the “default value” for a type. Read more
Source§

impl Send for MiniTimer

Source§

impl Sync for MiniTimer

Auto Trait Implementations§

Blanket Implementations§

Source§

impl<T> Any for T
where T: 'static + ?Sized,

Source§

fn type_id(&self) -> TypeId

Gets the TypeId of self. Read more
Source§

impl<T> Borrow<T> for T
where T: ?Sized,

Source§

fn borrow(&self) -> &T

Immutably borrows from an owned value. Read more
Source§

impl<T> BorrowMut<T> for T
where T: ?Sized,

Source§

fn borrow_mut(&mut self) -> &mut T

Mutably borrows from an owned value. Read more
Source§

impl<T> CloneToUninit for T
where T: Clone,

Source§

unsafe fn clone_to_uninit(&self, dest: *mut u8)

🔬This is a nightly-only experimental API. (clone_to_uninit)
Performs copy-assignment from self to dest. Read more
Source§

impl<T> From<T> for T

Source§

fn from(t: T) -> T

Returns the argument unchanged.

Source§

impl<T, U> Into<U> for T
where U: From<T>,

Source§

fn into(self) -> U

Calls U::from(self).

That is, this conversion is whatever the implementation of From<T> for U chooses to do.

Source§

impl<T> ToOwned for T
where T: Clone,

Source§

type Owned = T

The resulting type after obtaining ownership.
Source§

fn to_owned(&self) -> T

Creates owned data from borrowed data, usually by cloning. Read more
Source§

fn clone_into(&self, target: &mut T)

Uses borrowed data to replace owned data, usually by cloning. Read more
Source§

impl<T, U> TryFrom<U> for T
where U: Into<T>,

Source§

type Error = Infallible

The type returned in the event of a conversion error.
Source§

fn try_from(value: U) -> Result<T, <T as TryFrom<U>>::Error>

Performs the conversion.
Source§

impl<T, U> TryInto<U> for T
where U: TryFrom<T>,

Source§

type Error = <U as TryFrom<T>>::Error

The type returned in the event of a conversion error.
Source§

fn try_into(self) -> Result<U, <U as TryFrom<T>>::Error>

Performs the conversion.