Struct lib_wc::sync::ShutdownListener
source · pub struct ShutdownListener { /* private fields */ }
Expand description
Listens for a shutdown signal.
Shutdown is signalled using a broadcast::Receiver
. Only a single value is
ever sent. Once a value has been sent via the broadcast channel, shutdown
should occur.
The ShutdownListener
struct listens for the signal and tracks that the signal has
been received. Callers may query for whether the shutdown signal has been
received or not.
Implementations§
source§impl ShutdownListener
impl ShutdownListener
sourcepub fn is_shutdown(&self) -> bool
pub fn is_shutdown(&self) -> bool
Returns true
if the shutdown signal has been received.
Examples
use lib_wc::sync::ShutdownController;
use tokio::task::spawn;
#[tokio::main]
async fn main() {
let shutdown = ShutdownController::new();
let mut shutdown_listener = shutdown.subscribe();
assert!(!shutdown_listener.is_shutdown());
// Spawn a task
let t = spawn({
async move {
shutdown_listener.recv().await;
assert!(shutdown_listener.is_shutdown());
}
});
shutdown.shutdown().await;
}
sourcepub async fn recv(&mut self)
pub async fn recv(&mut self)
Receive the shutdown notice, waiting if necessary.
Examples
use tokio::select;
use lib_wc::sync::ShutdownListener;
use lib_wc::sync::RateLimiter;
/// A task that continuously does work at a fixed rate, but exits when shutdown is initiated.
async fn long_lived_task(mut shutdown: ShutdownListener, rate_limiter: RateLimiter) {
while !shutdown.is_shutdown() {
select! {
_ = shutdown.recv() => { return; }
_ = rate_limiter.throttle(|| async { /* do work */ }) => { println!("tick"); }
}
}
}