graceful_shutdown/
graceful_shutdown.rs

1//! Run with `cargo run --example graceful_shutdown` command.
2//!
3//! To connect through browser, navigate to "http://localhost:3000" url.
4//!
5//! After 10 seconds:
6//!  - If there aren't any connections alive, server will shutdown.
7//!  - If there are connections alive, server will wait until deadline is elapsed.
8//!  - Deadline is 30 seconds. Server will shutdown anyways when deadline is elapsed.
9
10use axum::{routing::get, Router};
11use axum_server::Handle;
12use std::{net::SocketAddr, time::Duration};
13use tokio::time::sleep;
14
15#[tokio::main]
16async fn main() {
17    let app = Router::new().route("/", get(|| async { "Hello, world!" }));
18
19    let handle = Handle::new();
20
21    // Spawn a task to gracefully shutdown server.
22    tokio::spawn(graceful_shutdown(handle.clone()));
23
24    let addr = SocketAddr::from(([127, 0, 0, 1], 3000));
25    println!("listening on {}", addr);
26    axum_server::bind(addr)
27        .handle(handle)
28        .serve(app.into_make_service())
29        .await
30        .unwrap();
31
32    println!("server is shut down");
33}
34
35async fn graceful_shutdown(handle: Handle) {
36    // Wait 10 seconds.
37    sleep(Duration::from_secs(10)).await;
38
39    println!("sending graceful shutdown signal");
40
41    // Signal the server to shutdown using Handle.
42    handle.graceful_shutdown(Some(Duration::from_secs(30)));
43
44    // Print alive connection count every second.
45    loop {
46        sleep(Duration::from_secs(1)).await;
47
48        println!("alive connections: {}", handle.connection_count());
49    }
50}