Skip to main content

simple/
simple.rs

1use std::time::Duration;
2
3use async_repeater::RepeaterEntry;
4
5/// Most basic struct for this to work.
6/// Only carries an id and an interval
7#[derive(Debug, Clone)]
8pub struct Entry {
9    id: u8,
10    interval: Duration,
11}
12
13impl Entry {
14    pub fn new(id: u8, interval: Duration) -> Self {
15        Self { id, interval }
16    }
17}
18
19impl RepeaterEntry for Entry {
20    type Key = u8;
21
22    fn interval(&self) -> Duration {
23        self.interval
24    }
25
26    fn key(&self) -> Self::Key {
27        self.id
28    }
29}
30
31#[tokio::main(flavor = "current_thread")]
32async fn main() {
33    let callback = |entry, _| async move { println!("Popped {entry:?}") };
34
35    // create and start the repeater
36    let handle = async_repeater::Repeater::with_capacity(25).run_with_async_callback(callback);
37
38    // create entries with the same interval
39    let dur = Duration::from_secs(5);
40    let repetition = vec![Entry::new(0, dur), Entry::new(1, dur), Entry::new(2, dur)];
41
42    // insert the entries into the repeater with 1 second delay in between
43    for repetition in repetition {
44        handle.insert(repetition).await.unwrap();
45        tokio::time::sleep(Duration::from_secs(1)).await;
46    }
47
48    // wait for a ctrl-c.
49    // If this wasn't there, the program would exit immidiatly without running
50    // a single repetition
51    tokio::signal::ctrl_c().await.unwrap();
52    handle.stop().await.unwrap();
53    println!("Stopping cycler");
54}