ScheduledExecutorService scheduleWithFixedDelay and scheduleAtFixedRate

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.

 

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值