如何有效取消定期调度执行器服务任务

2022-09-02 13:47:48

那么,使用此链接作为参考,任何人都可以建议一个更优雅的解决方案来取消定期的 ScheduledExecutorService 任务吗?

以下是我当前正在执行的操作的示例:

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

答案 1

我建议您使用int并自己安排任务。

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

答案 2