Struct lib_wc::sync::ShutdownController
source · pub struct ShutdownController { /* private fields */ }
Expand description
A ShutdownController
is used to control the shutdown of an application.
ShutdownController::shutdown
is used signal that the application is shutting down
and should wait for all pending tasks to complete.
This is useful for things like web servers and database connections, etc where you want to allow all in-flight processing to complete before shutting down in order to maintain a consistent state.
Examples
use lib_wc::sync::ShutdownController;
use tokio::task::spawn;
#[tokio::main]
async fn main() {
let shutdown = ShutdownController::new();
let t = spawn({
let mut shutdown_listener = shutdown.subscribe();
assert!(!shutdown_listener.is_shutdown());
async move {
shutdown_listener.recv().await;
assert!(shutdown_listener.is_shutdown());
}
});
shutdown.shutdown().await;
}
Implementations§
source§impl ShutdownController
impl ShutdownController
sourcepub fn subscribe(&self) -> ShutdownListener
pub fn subscribe(&self) -> ShutdownListener
Create a new ShutdownListener
instance that can listen for the shutdown signal.
Examples
use lib_wc::sync::{ShutdownController, ShutdownListener};
let shutdown = ShutdownController::new();
let shutdown_listener = shutdown.subscribe();
sourcepub async fn shutdown(self)
pub async fn shutdown(self)
Begin shutting down and wait for all ShutdownListener
instances to be dropped.
Examples
use std::time::Duration;
use tokio::time::interval;
use tokio::task::spawn;
use tokio::sync::{broadcast, mpsc};
use lib_wc::sync::{ShutdownController, ShutdownListener};
async fn task(mut shutdown: ShutdownListener) {
let mut interval = interval(Duration::from_nanos(100));
while !shutdown.is_shutdown() {
tokio::select! {
_ = interval.tick() => {
println!("tick");
}
_ = shutdown.recv() => {
println!("shutdown");
break;
}
}
}
}
#[tokio::main]
async fn main() {
let shutdown = ShutdownController::new();
// Spawn a task
let t = spawn({
let shutdown_listener = shutdown.subscribe();
async move { task(shutdown_listener).await }
});
// Wait for the task to finish
shutdown.shutdown().await;
}