polkadot_node_metrics/
metronome.rs1use futures::prelude::*;
18use futures_timer::Delay;
19use std::{
20 pin::Pin,
21 task::{Context, Poll},
22 time::Duration,
23};
24
25#[derive(Copy, Clone)]
26enum MetronomeState {
27 Snooze,
28 SetAlarm,
29}
30
31pub struct Metronome {
33 delay: Delay,
34 period: Duration,
35 state: MetronomeState,
36}
37
38impl Metronome {
39 pub fn new(cycle: Duration) -> Self {
41 let period = cycle.into();
42 Self { period, delay: Delay::new(period), state: MetronomeState::Snooze }
43 }
44}
45
46impl futures::Stream for Metronome {
47 type Item = ();
48 fn poll_next(mut self: Pin<&mut Self>, cx: &mut Context<'_>) -> Poll<Option<Self::Item>> {
49 loop {
50 match self.state {
51 MetronomeState::SetAlarm => {
52 let val = self.period;
53 self.delay.reset(val);
54 self.state = MetronomeState::Snooze;
55 },
56 MetronomeState::Snooze => {
57 if !Pin::new(&mut self.delay).poll(cx).is_ready() {
58 break
59 }
60 self.state = MetronomeState::SetAlarm;
61 return Poll::Ready(Some(()))
62 },
63 }
64 }
65 Poll::Pending
66 }
67}