Spring webapp - 在应用程序停止时关闭线程 [英] Spring webapp - shutting down threads on Application stop
问题描述
我使用Spring的ApplicationListener接口实例化ScheduledExecutorService,如下所示:
I am instantiating a ScheduledExecutorService using Spring's ApplicationListener interface as follows:
@Component
public class ExecutorsStart implements ApplicationListener<ContextRefreshedEvent> {
private ScheduledExecutorService executor;
@Autowired
Scheduler scheduler;
@Override
public void onApplicationEvent(final ContextRefreshedEvent event) {
executor = Executors.newSingleThreadScheduledExecutor();
scheduler.init();
int delay = 10;
int period = 60;// repeat every 1 minutes.
executor.scheduleAtFixedRate(scheduler, delay, period, TimeUnit.SECONDS);
}
目前,当我跑步时,Tomcat不会干净地关闭。 /shutdown.sh,带消息:
At the moment, Tomcat won't shut down cleanly when I run, ./shutdown.sh, with message:
The web application [/foo] appears to have started a thread named [pool-1-thread-1] but has failed to stop it
这似乎是因为我还没有编写代码以停止ScheduledExecutorService。
and this seems to be because I have not yet written code to stop the ScheduledExecutorService.
我的问题是:在这种环境下如何正确完成?
My question is: how should this be done properly in this environment?
我注意到存在 ContextStoppedEvent ,我为它实现了一个监听器:
I noticed that there exists a ContextStoppedEvent, so, I implemented a listener for it:
@Component
public class ExecutorsStop implements ApplicationListener<ContextStoppedEvent> {
@Autowired
ExecutorsStart executorsStart;
@Override
public void onApplicationEvent(final ContextStoppedEvent event) {
executorsStart.executor.shutdownNow();
}
但是当Tomcat关闭时,似乎没有调用此事件处理程序。
But it seems that this event handler doesn't get called when Tomcat is shutdown.
我是否错误地实现了这一点,或者我是否完全采用了这种方式?
Have I implemented this incorrectly, or am I going about this completely the wong way?
推荐答案
您正在寻找 ContextClosedEvent
。
@Component
public class ExecutorsStop implements ApplicationListener<ContextClosedEvent> {
@Autowired
ExecutorsStart executorsStart;
@Override
public void onApplicationEvent(final ContextClosedEvent event) {
System.out.println("Stopped: " + event);
}
}
当Servlet容器关闭时,它调用 contextDestroyed(..)
关于其各种 ServletContextListener
和 destroy()
在其 Servlet
实例上。 ContextLoaderListener
和 DispatcherServlet
每次调用 close()
on他们的 ApplicationContext
。
When the Servlet container shuts down, it calls contextDestroyed(..)
on its various ServletContextListener
and destroy()
on its Servlet
instances. The ContextLoaderListener
and DispatcherServlet
each call close()
on their ApplicationContext
.
这篇关于Spring webapp - 在应用程序停止时关闭线程的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!