use std::time::Duration;
use tokio::sync::watch;
#[derive(Clone, Debug)]
pub struct Shutdown {
rx: watch::Receiver<bool>,
}
#[derive(Clone, Debug)]
pub struct ShutdownSender {
tx: watch::Sender<bool>,
}
impl Shutdown {
pub fn new() -> (ShutdownSender, Shutdown) {
let (tx, rx) = watch::channel(false);
(ShutdownSender { tx }, Shutdown { rx })
}
pub fn is_cancelled(&self) -> bool {
*self.rx.borrow()
}
pub async fn wait_cancelled(&self) {
while !self.is_cancelled() {
tokio::time::sleep(Duration::from_millis(10)).await;
}
}
pub fn install_ctrl_c() -> Shutdown {
let (tx, rx) = Self::new();
tokio::spawn(async move {
if tokio::signal::ctrl_c().await.is_ok() {
tx.cancel();
}
});
rx
}
}
impl ShutdownSender {
pub fn cancel(&self) {
let _ = self.tx.send(true);
}
}