Timer TimerTask schedule scheduleAtFixedRate

本文通过一个具体的Java Timer示例展示了其工作原理,并解释了schedule与scheduleAtFixedRate方法的区别,帮助理解任务调度的时间间隔是如何计算的。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

 

jdk 自带的 timer 框架是有缺陷的, 其功能简单,而且有时候它的api 不好理解。

import java.util.Date;
import java.util.Timer;
import java.util.TimerTask;

public class TestTimer {

    private static final int delay = 1000;

    /**
     * @param args
     */
    public static void main(String[] args) {
        Timer t = new Timer();
        int seconds = 2;
        TimerTask task = new SimpleTask();
        t.schedule(task , delay, seconds * 1000);
    }

}

class SimpleTask extends TimerTask{

    @Override
    public void run() {
        
        System.out.println("SimpleTask.run() 11 " + new Date());
        
        try {
            Thread.sleep(4000);
        } catch (InterruptedException e) {
            e.printStackTrace();
        }

        //System.out.println("SimpleTask.run() 22 " + new Date());
    }
    
    
}

 

结果为

SimpleTask.run() 11 Mon May 30 16:43:58 CST 2016
SimpleTask.run() 11 Mon May 30 16:44:02 CST 2016
SimpleTask.run() 11 Mon May 30 16:44:06 CST 2016

 

显示是每隔4秒, 而不是我想象的 period +  sleep time  即 2+4 = 6s, why ??

 

原来是这样的:

参考: http://stackoverflow.com/questions/15128937/java-util-timer-fixed-delay-not-working

Nope, that's how it is intended to work. The period is the period between start times, not the period between an end time and the next start time.

Basically you're telling it in plain english "start at 1 second and execute every two seconds after that" so 1, 3, 5, 7, etc is the logical interpretation.

shareimprove this answer
answered Feb 28 '13 at 6:34

Affe
31k25064

Ok, I re-read the Javadoc again. That means 'schedule' uses previous task's start-time as reference (2nd task will reference 1st task, 3rd task will reference 2nd task). While 'scheduleAtFixedRate' always use the first task's start-time as reference (all task's start-time are based on the 1st task's start-time). Is that how it works? – Dave Xenos Feb 28 '13 at 6:52

Yeah, the way I think of it is if 'schedule' misses one, it forgets about it, if 'scheduleAtFixedRate' misses one, it puts in a make-up. – Affe Mar 1 '13 at 2:17

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值