Question

I am using ScheduledExecutorService in a J2EE application to schedule a task every x seconds taken from a config file (picks up data from a database and sends them to a external server). My code is:

try{
    final ScheduledExecutorService service = Executors.newSingleThreadScheduledExecutor();
    service.scheduleWithFixedDelay(new Runnable(){
    public void run(){
                RsaBaseAction rsa = RsaBaseAction.getInstance();//class that does all the work
                rsa.rsaBaseAction();
            }
          }, 0, timeInterval, TimeUnit.SECONDS);
     }
     catch(Exception ex){
         ex.printStackTrace();
     }

My question is is there any extra code I should be writing? Should I write a while loop to make sure thread is completed then do a service.shutdown() or does ScheduledExecutorService take care of that for me?

Was it helpful?

Solution

You would call shutdown if you wanted the scheduler to stop scheduling the events. You don't need to explicitly do this as if you want it to run for the lifetime of your application. You would use the shutdown method if for some reason the scheduling no longer made any sense.

An example. You're writing a CMS that offers integration with google shopping to upload product information. If the user removes their upload information (ie turned it off), you could call shutdown to stop the service doing the synchronization.

OTHER TIPS

As the Javadoc on the shutdown method clearly states:

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. This method does not wait for previously submitted tasks to complete execution. Use awaitTermination to do that.

I.e. previous tasks are going to be finished, no new ones are going to be done, however a previous task may continue past the shutdown command if it takes a while.

As for the code you have - I do not see any reason for the try-catch block. Scheduling tasks does not throw any exceptions. It looks like you want to actually try-catch the rsaBaseAction instead of the scheduling (if an exception is thrown by the runnable, no more executions are scheduled and the exception is handled by the thread group exception handler)

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top