Skip to main content

stream_impl/
stream_impl.rs

1//! This example uses the stream implementation on the DelayQueue directly.
2//! It skips the handle
3
4use async_repeater::{Repeater, RepeaterEntry};
5use std::time::Duration;
6use tokio_stream::StreamExt;
7
8/// Most basic struct for this to work.
9/// Only carries an id and an interval
10#[derive(Debug, Clone)]
11pub struct Entry {
12    id: u8,
13    interval: Duration,
14}
15
16impl Entry {
17    pub fn new(id: u8, interval: Duration) -> Self {
18        Self { id, interval }
19    }
20}
21
22impl RepeaterEntry for Entry {
23    type Key = u8;
24
25    fn interval(&self) -> Duration {
26        self.interval
27    }
28
29    fn key(&self) -> Self::Key {
30        self.id
31    }
32}
33
34#[tokio::main(flavor = "current_thread")]
35async fn main() {
36    // create but not start the repeater
37    let mut repeater = Repeater::<Entry>::with_capacity(7);
38
39    // create entries as a stream
40    let repetitions = tokio_stream::iter(vec![
41        Entry::new(0, Duration::from_millis(3000)),
42        Entry::new(1, Duration::from_millis(1000)),
43        Entry::new(2, Duration::from_millis(2000)),
44    ]);
45    tokio::pin!(repetitions);
46
47    // select either an element from the stream or
48    // an element from the repeater or
49    // from the ctrl-c signal
50    loop {
51        tokio::select! {
52            Some(item) = repeater.next() => {
53                println!("Popped: {item:?}");
54                repeater.insert(item);
55            }
56            Some(item) = repetitions.next() => {
57                repeater.insert(item);
58            }
59            _ = tokio::signal::ctrl_c() => {
60                break
61            }
62        }
63    }
64}