Skip to main content

TaskBuilder

Struct TaskBuilder 

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

Builder for creating Task instances.

Allows configuration of task frequency, concurrency limits, and other properties before building a Task.

Implementations§

Source§

impl TaskBuilder

Source

pub fn new(task_id: u64) -> Self

Creates a new TaskBuilder with the given task ID.

§Arguments
  • task_id - Unique identifier for the task
Examples found in repository?
examples/once_delayed_task.rs (line 22)
19async fn main() {
20    let timer = minitimer::MiniTimer::new();
21
22    let task = TaskBuilder::new(1)
23        .with_frequency_once_by_seconds(3)
24        .spawn_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 26)
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        .spawn_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 26)
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        .spawn_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 45)
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            .spawn_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 22)
19async fn main() {
20    let timer = minitimer::MiniTimer::new();
21
22    let task1 = TaskBuilder::new(1)
23        .with_frequency_repeated_by_seconds(2)
24        .spawn_async(SimpleTask { id: 1 })
25        .unwrap();
26
27    let task2 = TaskBuilder::new(2)
28        .with_frequency_once_by_seconds(5)
29        .spawn_async(SimpleTask { id: 2 })
30        .unwrap();
31
32    let task3 = TaskBuilder::new(3)
33        .with_frequency_count_down_by_seconds(3, 1)
34        .spawn_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 28)
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        .spawn_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        .spawn_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 with_frequency_once_by_seconds(&mut self, seconds: u64) -> &mut Self

Sets the task to execute once after the specified number of seconds.

§Arguments
  • seconds - Number of seconds to wait before execution
Examples found in repository?
examples/once_delayed_task.rs (line 23)
19async fn main() {
20    let timer = minitimer::MiniTimer::new();
21
22    let task = TaskBuilder::new(1)
23        .with_frequency_once_by_seconds(3)
24        .spawn_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/concurrency_control.rs (line 46)
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            .spawn_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 28)
19async fn main() {
20    let timer = minitimer::MiniTimer::new();
21
22    let task1 = TaskBuilder::new(1)
23        .with_frequency_repeated_by_seconds(2)
24        .spawn_async(SimpleTask { id: 1 })
25        .unwrap();
26
27    let task2 = TaskBuilder::new(2)
28        .with_frequency_once_by_seconds(5)
29        .spawn_async(SimpleTask { id: 2 })
30        .unwrap();
31
32    let task3 = TaskBuilder::new(3)
33        .with_frequency_count_down_by_seconds(3, 1)
34        .spawn_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 with_frequency_repeated_by_seconds(&mut self, seconds: u64) -> &mut Self

Sets the task to execute repeatedly at the specified interval.

§Arguments
  • seconds - Interval in seconds between executions
Examples found in repository?
examples/repeated_task.rs (line 27)
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        .spawn_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}
More examples
Hide additional examples
examples/task_management.rs (line 23)
19async fn main() {
20    let timer = minitimer::MiniTimer::new();
21
22    let task1 = TaskBuilder::new(1)
23        .with_frequency_repeated_by_seconds(2)
24        .spawn_async(SimpleTask { id: 1 })
25        .unwrap();
26
27    let task2 = TaskBuilder::new(2)
28        .with_frequency_once_by_seconds(5)
29        .spawn_async(SimpleTask { id: 2 })
30        .unwrap();
31
32    let task3 = TaskBuilder::new(3)
33        .with_frequency_count_down_by_seconds(3, 1)
34        .spawn_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 29)
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        .spawn_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        .spawn_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 with_max_concurrency(&mut self, max: usize) -> &mut Self

Sets the maximum number of concurrent executions for this task.

§Arguments
  • max - Maximum number of concurrent executions
Examples found in repository?
examples/concurrency_control.rs (line 47)
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            .spawn_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}
Source

pub fn with_frequency_count_down_by_seconds( &mut self, count_down: u64, seconds: u64, ) -> &mut Self

Sets the task to execute a specific number of times at the specified interval.

§Arguments
  • count_down - Number of times the task will execute
  • seconds - Interval in seconds between executions
Examples found in repository?
examples/countdown_task.rs (line 27)
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        .spawn_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}
More examples
Hide additional examples
examples/task_management.rs (line 33)
19async fn main() {
20    let timer = minitimer::MiniTimer::new();
21
22    let task1 = TaskBuilder::new(1)
23        .with_frequency_repeated_by_seconds(2)
24        .spawn_async(SimpleTask { id: 1 })
25        .unwrap();
26
27    let task2 = TaskBuilder::new(2)
28        .with_frequency_once_by_seconds(5)
29        .spawn_async(SimpleTask { id: 2 })
30        .unwrap();
31
32    let task3 = TaskBuilder::new(3)
33        .with_frequency_count_down_by_seconds(3, 1)
34        .spawn_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 with_frequency_once_by_timestamp_seconds( &mut self, timestamp: u64, ) -> Result<&mut Self, TaskError>

Sets the task to execute once at the specified Unix timestamp.

§Arguments
  • timestamp - Unix timestamp (seconds since epoch) when the task should execute
§Returns
  • Ok(&mut Self) - If the timestamp is in the future
  • Err(TaskError) - If the timestamp is in the past or now
Source

pub fn spawn_async<T: TaskRunner<Output = ()> + Send + Sync>( self, task_runner: T, ) -> Result<Task, TaskError>

Builds and returns a Task with the configured settings.

§Arguments
  • task_runner - The runner that defines what the task does
§Returns
  • Ok(Task) - If the task was successfully built
  • Err(TaskError) - If there was an error building the task
Examples found in repository?
examples/once_delayed_task.rs (lines 24-26)
19async fn main() {
20    let timer = minitimer::MiniTimer::new();
21
22    let task = TaskBuilder::new(1)
23        .with_frequency_once_by_seconds(3)
24        .spawn_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 (lines 28-30)
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        .spawn_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 (lines 28-30)
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        .spawn_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 (lines 48-51)
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            .spawn_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 24)
19async fn main() {
20    let timer = minitimer::MiniTimer::new();
21
22    let task1 = TaskBuilder::new(1)
23        .with_frequency_repeated_by_seconds(2)
24        .spawn_async(SimpleTask { id: 1 })
25        .unwrap();
26
27    let task2 = TaskBuilder::new(2)
28        .with_frequency_once_by_seconds(5)
29        .spawn_async(SimpleTask { id: 2 })
30        .unwrap();
31
32    let task3 = TaskBuilder::new(3)
33        .with_frequency_count_down_by_seconds(3, 1)
34        .spawn_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 (lines 30-33)
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        .spawn_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        .spawn_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}

Trait Implementations§

Source§

impl Clone for TaskBuilder

Source§

fn clone(&self) -> TaskBuilder

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 TaskBuilder

Source§

fn default() -> TaskBuilder

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

impl Copy for TaskBuilder

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.