shutdown/
shutdown.rs

1//! Run with `cargo run --example shutdown` command.
2//!
3//! To connect through browser, navigate to "http://localhost:3000" url.
4//!
5//! Server will shutdown in 20 seconds.
6
7use axum::{routing::get, Router};
8use hyper_serve::Handle;
9use std::{net::SocketAddr, time::Duration};
10use tokio::time::sleep;
11
12#[tokio::main]
13async fn main() {
14    let app = Router::new().route("/", get(|| async { "Hello, world!" }));
15
16    let handle = Handle::new();
17
18    // Spawn a task to shutdown server.
19    tokio::spawn(shutdown(handle.clone()));
20
21    let addr = SocketAddr::from(([127, 0, 0, 1], 3000));
22    println!("listening on {}", addr);
23    hyper_serve::bind(addr)
24        .handle(handle)
25        .serve(app.into_make_service())
26        .await
27        .unwrap();
28
29    println!("server is shut down");
30}
31
32async fn shutdown(handle: Handle) {
33    // Wait 20 seconds.
34    sleep(Duration::from_secs(20)).await;
35
36    println!("sending shutdown signal");
37
38    // Signal the server to shutdown using Handle.
39    handle.shutdown();
40}