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
use tokio::signal;
use tokio::sync::{mpsc};
use anyhow::anyhow;

struct CtrlCActor {
    notification_channel: tokio::sync::watch::Sender<bool>,
}

impl CtrlCActor {

    fn new(notification_channel: tokio::sync::watch::Sender<bool>) -> Self { 
        CtrlCActor { notification_channel } 
    }

    fn ctrlc_announce(self) {
        self.notification_channel.send(true);
    }
}

async fn run(actor: CtrlCActor) {
    println!("Running... CtrlCActor");

    signal::ctrl_c().await.expect("Problem with Ctrl C");

    println!("Exiting after Ctr+C");

    actor.notification_channel.send(true).expect("Problem sending signal");
}


#[derive(Clone)]
pub struct CtrlCActorHandle {
    notification_channel: tokio::sync::watch::Receiver<bool>,
}

impl CtrlCActorHandle {

    pub fn new() -> Self {
        let (sender, receiver) = tokio::sync::watch::channel(false);

        let actor = CtrlCActor::new(sender);

        tokio::spawn(run(actor));

        Self { notification_channel: receiver }
    }

    pub async fn wait_for_shutdown(&mut self) -> anyhow::Result<()> {

        self.notification_channel.changed().await;

        Ok(())
    }

}