简体   繁体   中英

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;
    }

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);
    }
}

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM