首页 > 其他 > 详细

Timer TimerTask schedule scheduleAtFixedRate

时间:2017-05-31 13:23:02      阅读:187      评论:0      收藏:0      [点我收藏+]

 

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

Timer TimerTask schedule scheduleAtFixedRate

原文:http://www.cnblogs.com/FlyAway2013/p/5543060.html

(0)
(0)
   
举报
评论 一句话评论(0
关于我们 - 联系我们 - 留言反馈 - 联系我们:wmxa8@hotmail.com
© 2014 bubuko.com 版权所有
打开技术之扣,分享程序人生!