zoukankan      html  css  js  c++  java
  • Timer TimerTask schedule scheduleAtFixedRate

    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

  • 相关阅读:
    SDN 实验室学生们
    面向对象程序设计
    软件工程实践
    走出舒适圈的信念和勇气——“Learning by doing!” 我的软工2020春季教学总结
    第二次作业(2)
    结对编程第一战——“停课不停学”数据可视化的数据采集
    团队作业第四次—项目系统设计与数据库设计
    团队作业第一次—团队展示
    软件工程实践2019第五次作业——结对编程的编程实现
    软件工程实践2019——idea表述及组队
  • 原文地址:https://www.cnblogs.com/FlyAway2013/p/5543060.html
Copyright © 2011-2022 走看看