Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to effectively cancel periodic ScheduledExecutorService task

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;
    }
like image 492
mre Avatar asked Mar 08 '11 14:03

mre


People also ask

How to cancel a task in ExecutorService?

Two different methods are provided for shutting down an ExecutorService. The shutdown() method will allow previously submitted tasks to execute before terminating, while the shutdownNow() method prevents waiting tasks from starting and attempts to stop currently executing tasks.

How to cancel Scheduled task Java?

In order to cancel the Timer Task in Java, we use the java. util. TimerTask. cancel() method.

Which method can cancel the future task triggered by submit () of ExecutorService?

You can cancel the task submitted to ExecutorService by simply calling the cancel method on the future submitted when the task is submitted.

Can we cancel callable task?

When we submit a task (Callable or its cousin Runnable) for execution to an Executor or ExecutorService (e.g. ThreadPoolExecutor), we get a Future back which wraps the tasks. It has a method called Future. cancel(...) which can be used to cancel the task the future wraps.


1 Answers

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);
    }
}
like image 155
Peter Lawrey Avatar answered Sep 18 '22 16:09

Peter Lawrey