1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
use crate::{Action, ActionPerformer, ActionRecipient, LiteTask, ShutdownReceiver};
use anyhow::Error;
use async_trait::async_trait;
use futures::{select, FutureExt, StreamExt};
use std::time::Duration;
use tokio::time::{interval, Instant};
#[derive(Debug)]
pub struct HeartBeat {
duration: Duration,
recipient: ActionRecipient<Tick>,
}
impl HeartBeat {
pub fn new<T>(duration: Duration, address: T) -> Self
where
ActionRecipient<Tick>: From<T>,
{
Self {
duration,
recipient: address.into(),
}
}
}
#[derive(Debug)]
pub struct Tick(pub Instant);
impl Action for Tick {}
#[async_trait]
impl LiteTask for HeartBeat {
async fn routine(mut self, signal: ShutdownReceiver) -> Result<(), Error> {
let mut ticks = interval(self.duration).map(Tick).fuse();
let done = signal.just_done().fuse();
tokio::pin!(done);
let recipient = &mut self.recipient;
loop {
select! {
_ = done => {
break;
}
tick = ticks.select_next_some() => {
recipient.act(tick).await?;
}
}
}
Ok(())
}
}