`
jusi
  • 浏览: 4736 次
  • 性别: Icon_minigender_1
  • 来自: 天津
社区版块
存档分类
最新评论

ScheduledExecutorService scheduleWithFixedDelay and scheduleAtFixedRate

    博客分类:
  • java
 
阅读更多

ScheduledExecutorService has 2 method to schedule a task

  • schedule with fixed delay
  • schedule at fixed rate

I was confused about delay and rate, they both require a time parameter. What's the difference?

I ran following code:

public static void main(String[] args) {
        ScheduledExecutorService executors = Executors.newSingleThreadScheduledExecutor();
        executors.scheduleWithFixedDelay(new Runnable() {
            @Override
            public void run() {
                System.out.println(new Date());
                try {
                    Thread.sleep(5000);
                } catch (InterruptedException e) {
                    e.printStackTrace();
                }
            }
        }, 0, 5, TimeUnit.SECONDS);
    }

 And I got such a result on console. It will print a log every 10 seconds.

Wed Dec 03 23:13:44 CST 2014
Wed Dec 03 23:13:54 CST 2014
Wed Dec 03 23:14:04 CST 2014

 I ran same code with the other method, this time I got:

Wed Dec 03 23:26:48 CST 2014
Wed Dec 03 23:26:53 CST 2014
Wed Dec 03 23:26:58 CST 2014

 

  • "schedule with fixed delay" would delay given time since last task finished to start next execution
  • "schedule at fixed rate" would wait given time since last task start to start next execution, if duration exceed given time, next task will be executed immediately.

 

分享到:
评论

相关推荐

Global site tag (gtag.js) - Google Analytics