Reputation: 19552
I have a ScheduledExecutorService
and I do a task every 15 mins (in a web application in Tomcat).
In a ServletContextListener
in contextDestroyed
I have done:
Runtime.getRuntime().addShutdownHook(new Thread(){
@Override
public void run(){
scheduler.shutdown();
}
});
The scheduler is started like:
final Runnable r = new Runnable(){
@Override
public void run() {
System.out.println("My task");
//Do some task
}
};
updater.scheduleWithFixedDelay(r, 30, 15, TimeUnit.MINUTES);
Question:On shutdown
any remaining task isn't executed.
There is a task running but I don't see any logs so it seems it is not executed. Why?
UPDATE:
If I start tomcat and then after 2 mins I shutdown then isn't the task considered as scheduled and must run? I mean if a task is submitted isn't it considered as pending? Or it must be actually running?
Upvotes: 1
Views: 336
Reputation: 1864
To explicitly wait until all running tasks are finished, do something like this:
try {
// Wait for one second indefinitively
while (!scheduler.awaitTermination (1, TimeUnit.SECONDS)) {
// wait until completion
}
} catch (final InterruptedException ex) {
// interrupted... you may log something
}
Upvotes: 1
Reputation: 116828
I can't quite parse your question but maybe your application is not exiting like you'd expect?
Shutting down an Executor
will stop any tasks for being submitted but any running tasks will continue to run until they exit. From the shutdown()
javadocs:
Initiates an orderly shutdown in which previously submitted tasks are executed, but no new tasks will be accepted. Invocation has no additional effect if already shut down.
If you edit your question to be more clear we can answer more appropriately.
Upvotes: 0