Skip to main content

countdown_task/
countdown_task.rs

1use async_trait::async_trait;
2use minitimer::{TaskBuilder, TaskRunner};
3
4struct CountDownTask {
5    counter: std::sync::Arc<std::sync::Mutex<u32>>,
6}
7
8#[async_trait]
9impl TaskRunner for CountDownTask {
10    type Output = ();
11
12    async fn run(&self) -> Result<Self::Output, Box<dyn std::error::Error + Send + Sync>> {
13        let mut counter = self.counter.lock().unwrap();
14        *counter += 1;
15        println!("CountDown task executed! Execution #{}", *counter);
16        Ok(())
17    }
18}
19
20#[tokio::main]
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}