一段时间后终止Spring Boot应用程序

时间:2018-05-06 18:30:39

标签: java

如何在一段时间后终止正在运行的Spring Boot应用程序?

换句话说,我今天将运行我的春季启动应用程序,我想从现在开始两天终止:

new SpringApplicationBuilder().sources(Main.class).run(args);

1 个答案:

答案 0 :(得分:1)

正式关闭文档中描述的spring boot应用程序的方法之一:https://docs.spring.io/spring-boot/docs/current-SNAPSHOT/reference/htmlsingle/#boot-features-application-exit

所以基本上要优雅地关闭Spring启动应用程序,你应该调用

System.exit(SpringApplication
                .exit(SpringApplication.run(ExitCodeApplication.class, args)));

为了安排此操作,您可以使用spring boot scherduled任务:https://docs.spring.io/spring/docs/3.2.x/spring-framework-reference/html/scheduling.html

总而言之,您将获得一些具有此方法的服务:

@Scheduled(fixedRate = 2 * MILLIS_IN_DAY, initialDelay = 2 * MILLIS_IN_DAY)
public void shutdownApp() {
    System.exit(SpringApplication
                .exit(SpringApplication.run(ExitCodeApplication.class, args)));
}

启用此预定方法后,您需要使用@EnableScheduling

为应用程序类添加注释