1

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?

0

2 Answers 2

1

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 } 
Sign up to request clarification or add additional context in comments.

Comments

0

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.

5 Comments

I run in Tomcat.The shutdown is inside the ServletContextListener. I stop using shutdown
Usually, you need to implement your own logic to either 1) process all (or some with a timeout) outstanding messages in the queue or 2) save the messages and process them when the application is restarted (usually done via JMQ with persistent queues)
I still don't quite understand your question @Jim. Can you edit the question and be more precise? You provide shutdown code but maybe your issues is that your background task isn't running at all?
@AngerClown:JMO?How is this related to my question?
I meant JMQ, as a way to store outstanding messages at shutdown.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.