I create a ScheduledExecutorService using the Spring 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;
executor.scheduleAtFixedRate(scheduler, delay, period, TimeUnit.SECONDS);
}
At the moment, Tomcat will not close when I start. /shutdown.sh, with the message:
The web application [/foo] appears to have started a thread named [pool-1-thread-1] but has failed to stop it
and it looks like I haven't written code yet to stop the ScheduledExecutorService.
My question is: how should this be done correctly in this environment?
I noticed that there is 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();
}
But it seems that this event handler is not called when Tomcat disconnects.
Am I doing it wrong, or am I going through it completely?
source
share