19

So, using this link as a reference, can anyone suggest a more elegant solution for canceling a periodic ScheduledExecutorService task?

Here's an example of what I'm currently doing:

// do stuff

// Schedule periodic task
currentTask = exec.scheduleAtFixedRate(
                            new RequestProgressRunnable(),
                            0, 
                            5000,
                            TimeUnit.MILLISECONDS);

// Runnable
private class RequestProgressRunnable implements Runnable
{
        // Field members
        private Integer progressValue = 0;

        @Override
        public void run()
        {
            // do stuff

            // Check progress value
            if (progressValue == 100)
            {
                // Cancel task
                getFuture().cancel(true);
            }
            else
            {
                // Increment progress value
                progressValue += 10;
            }
        }
    }

    /**
     * Gets the future object of the scheduled task
     * @return Future object
     */
    public Future<?> getFuture()
    {
        return currentTask;
    }
Community
  • 1
  • 1
mre
  • 43,520
  • 33
  • 120
  • 170
  • 1
    The only other ways I can think of are shutting down the executor or throwing an exception from `run()`. I don't think either are more elegant. – Mark Peters Mar 08 '11 at 14:42
  • 1
    btw using 'Integer' for a counter totally wrecks any idea of 'elegant' solution, it's plain ugly. – bestsss Mar 08 '11 at 17:33

1 Answers1

15

I suggest you use int and schedule the task yourself.

executor.schedule(new RequestProgressRunnable(), 5000, TimeUnit.MILLISECONDS);

class RequestProgressRunnable implements Runnable {
    private int count = 0;
    public void run() {
        // do stuff

        // Increment progress value
        progressValue += 10;

        // Check progress value
        if (progressValue < 100)
            executor.schedule(this, 5000, TimeUnit.MILLISECONDS);
    }
}
Peter Lawrey
  • 525,659
  • 79
  • 751
  • 1,130
  • 3
    this is actually `scheduleWithFixedDelay` not `scheduleAtFixedRate`. Still if you have access to the executor, calling cancel at the returned future is just easier. – bestsss Mar 08 '11 at 17:31
  • 5
    @bestsss, this may be true but getting a handle to the future is trickier because you don't have it until after the Runnable is constructed and scheduled. You run the risk the future is not set when you try to cancel it. ;) – Peter Lawrey Mar 09 '11 at 08:02