use std::time::Duration;
use tokio::sync::watch;
#[derive(Debug)]
pub(crate) struct ShutdownSignal {
sender: watch::Sender<bool>,
}
impl Default for ShutdownSignal {
fn default() -> Self {
Self {
sender: watch::channel(false).0,
}
}
}
impl ShutdownSignal {
pub(crate) fn is_requested(&self) -> bool {
*self.sender.borrow()
}
pub(crate) fn request(&self) {
self.sender.send_replace(true);
}
pub(crate) async fn wait(&self) {
let mut receiver = self.sender.subscribe();
while !*receiver.borrow_and_update() {
if receiver.changed().await.is_err() {
return;
}
}
}
pub(crate) async fn sleep(&self, duration: Duration) {
tokio::select! {
_ = tokio::time::sleep(duration) => {}
_ = self.wait() => {}
}
}
}
#[cfg(test)]
#[path = "shutdown_tests.rs"]
mod tests;