Shutdown timeout
#1894
-
What would be the proper way of setting a shutdown timeout of an axum server? What I would like to achieve is for the server to shut down after a set deadline to prevent dangling requests. let router = Router::new().route("/", get(handler));
let addr = SocketAddr::from(([0, 0, 0, 0], 3000));
axum::Server::bind(&addr)
.serve(router.into_make_service())
.with_graceful_shutdown(shutdown_signal())
.await
.unwrap();
async fn handler() -> &'static str {
time::sleep(Duration::from_secs(10)).await;
}
async fn shutdown_signal() {
let ctrl_c = async {
signal::ctrl_c()
.await
.expect("failed to install Ctrl+C handler");
};
let terminate = async {
signal::unix::signal(signal::unix::SignalKind::terminate())
.expect("failed to install signal handler")
.recv()
.await;
};
tokio::select! {
_ = ctrl_c => {},
_ = terminate => {},
}
} For example in go, one can make a context with a timeout and pass it into the shutdown method of the server. When the context deadline is exceeded, the process will terminate. Obviously the rust version will hang untill the duration in the handler has elapsed. shutdown := make(chan os.Signal, 1)
signal.Notify(shutdown, syscall.SIGINT, syscall.SIGTERM)
handler := func(w http.ResponseWriter, r *http.Request) {
time.Sleep(10*time.Second)
}
srv := http.Server{
Addr: "0.0.0.0:3000",
Handler: http.HandlerFunc(handler),
}
_ = srv.ListenAndServe()
select {
case <-shutdown:
ctx, cancel := context.WithTimeout(context.Background(), 5*time.Second)
defer cancel()
_ = srv.Shutdown(ctx)
} |
Beta Was this translation helpful? Give feedback.
Answered by
yanns
Oct 8, 2024
Replies: 1 comment
-
Inside the tokio::select!, could you wait for a timeout. Something like: let timeout = tokio::time::sleep(std::time::Duration::from_secs(5));
tokio::select! {
_ = ctrl_c => {},
_ = terminate => {},
_ = timeout => {},
} |
Beta Was this translation helpful? Give feedback.
0 replies
Answer selected by
yanns
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
Inside the tokio::select!, could you wait for a timeout. Something like: