Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to gracefuly shutdown a Spring Boot application by start-stop-daemon [duplicate]

We have a multithreaded Spring Boot Application, which runs on Linux machine as a daemon. When I try to stop the application by start-stop-daemon like this

start-stop-daemon --stop --quiet --retry=TERM/30/KILL/5 --pidfile $PIDFILE --name $NAME

The SIGTERM signal is sent and application immetiately ends. However I want the application to wait, until every thread finishes it's work.

Is there any way, how to manage what happens, when SIGTERM signal is received?

like image 927
Michal Krasny Avatar asked Apr 18 '16 10:04

Michal Krasny


2 Answers

sample as mentioned by @Evgeny

@SpringBootApplication
@Slf4j
public class SpringBootShutdownHookApplication {

  public static void main(String[] args) {
    SpringApplication.run(SpringBootShutdownHookApplication.class, args);
  }

  @PreDestroy
  public void onExit() {
    log.info("###STOPing###");
    try {
      Thread.sleep(5 * 1000);
    } catch (InterruptedException e) {
      log.error("", e);;
    }
    log.info("###STOP FROM THE LIFECYCLE###");
  }
}
like image 65
lizhipeng Avatar answered Oct 06 '22 12:10

lizhipeng


Spring Boot app registers a shutdown hook with the JVM to ensure that the ApplicationContext is closed gracefully on exit. Create bean (or beans) that implements DisposableBean or has method with @PreDestroy annotation. This bean will be invoked on app shutdown.

http://docs.spring.io/spring-boot/docs/current-SNAPSHOT/reference/htmlsingle/#boot-features-application-exit

like image 42
Evgeny Avatar answered Oct 06 '22 14:10

Evgeny