javatimertimertask

Pausing the timer


I've the following code in my Java component. The method myLongRunningTask() gets called on every 5 second timer interval. I need to be able to pause the timer until myLongRunningTask() method execution is completed. Wondering if this is possible? Any thoughts would be appreciated! (I tried using timer.cancel,but i believe it will discard any currently scheduled tasks.)

Thanks.

    Timer timer = new Timer();
    TimerTask timerTask = new TimerTask() {
    
    @Override
    public void run() {
        myLongRunningTask();    
    }
  };
    
    timer.schedule(timerTask, 2 * 1000, 5 * 1000);

Solution

  • The Timer and TimerTask classes are legacy, having been supplanted by the Executors framework way back in Java 5. So noted in their Javadoc.

    One of the Executor sub-interfaces is ScheduledExecutorService. You can use this to schedule a repeating task. You have two choices in how to make that repeating schedule:

    You seem to want: After one execution ends, wait five seconds until the next execution begins. If that interpretation of your Question is correct, you want the second approach bulleted above.

    ScheduledExecutorService ses = Executors.newSingleThreadScheduledExecutor() ;
    ses.scheduleWithFixedDelay( myRunnableTask, … , 5 , TimeUnit.SECONDS );
    

    To learn more about executor services, and most especially about how important it is to (a) not let an Exception bubble up and (b) properly shut them down before your app ends, search Stack Overflow. The topic has been addressed many times.


    Caveat: If your app deploys to a Jakarta EE compliant server that supports Jakarta Concurrency, use a managed scheduled executor service there rather than the code shown above.