首页
学习
活动
专区
工具
TVP
发布
社区首页 >问答首页 >如何有效地取消周期性ScheduledExecutorService任务

如何有效地取消周期性ScheduledExecutorService任务
EN

Stack Overflow用户
提问于 2011-03-08 22:35:55
回答 1查看 13K关注 0票数 18

因此,使用this链接作为参考,有没有人能推荐一个更优雅的解决方案来取消周期性的ScheduledExecutorService任务?

下面是我目前正在做的一个例子:

代码语言:javascript
复制
// 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;
    }
EN

回答 1

Stack Overflow用户

回答已采纳

发布于 2011-03-08 22:43:55

我建议你使用int并自己调度任务。

代码语言:javascript
复制
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);
    }
}
票数 15
EN
页面原文内容由Stack Overflow提供。腾讯云小微IT领域专用引擎提供翻译支持
原文链接:

https://stackoverflow.com/questions/5233893

复制
相关文章

相似问题

领券
问题归档专栏文章快讯文章归档关键词归档开发者手册归档开发者手册 Section 归档