简体   繁体   English

Java util.timer固定延迟不起作用?

[英]Java util.timer fixed delay not working?

I tried to see how a timer's fixed delay method (schedule) works but looks like i failed. 我试着看看计时器的固定延迟方法(计划)是如何工作的,但看起来我失败了。

This is my code : 这是我的代码:

public class Timer_Test {    
  static Timer _a_timer;
  static int num_o_proc = 0;
  static int timer_call = 0;
  static double prog_begin_time;

public static void main(String[] args) {
    prog_begin_time = System.currentTimeMillis();

    _a_timer = new Timer();

    _a_timer.schedule(new TimerTask() {
        @Override
        public void run() {
            timer_call++;
            System.out.println(timer_call + " timer start   at " + (System.currentTimeMillis() - prog_begin_time));
            process();


            System.out.println(timer_call + " timer end   at " + (System.currentTimeMillis() - prog_begin_time));
            if (timer_call >= 5) {
                System.exit(0);
            }
        }
    }, 1000, 2000);
}

public static void process() {
    num_o_proc++;
    int local_num_o_proc = num_o_proc;
    System.out.println(local_num_o_proc + " process start   at " + (System.currentTimeMillis() - prog_begin_time));

    double _a_ = 0;
    for(int x=0; x<Integer.MAX_VALUE/2; x++) {
        _a_++;
    }
    System.out.println(local_num_o_proc + " process end   at " + (System.currentTimeMillis() - prog_begin_time));
  }
}

This is what I get : 这就是我得到的:

1 timer start at 1000.0 1个计时器从1000.0开始

1 process start at 1000.0 1个过程从1000.0开始

1 process end at 2109.0 1个过程结束于2109.0

1 timer end at 2109.0 1个计时器结束于2109.0

2 timer start at 3000.0 2计时器从3000.0开始

2 process start at 3000.0 2过程从3000.0开始

2 process end at 4109.0 2过程结束于4109.0

2 timer end at 4109.0 2计时器结束于4109.0

3 timer start at 5000.0 3计时器从5000.0开始

3 process start at 5000.0 3流程从5000.0开始

3 process end at 6109.0 ..... 3流程结束于6109.0 .....

Shouldn't timer 2 start at 4109 (instead of 3000) since the first timer task ended at 2109 (2109 + 2000)? 由于第一个计时器任务在2109(2109 + 2000)结束,计时器2不应该从4109(而不是3000)开始吗? I tried using 'scheduleAtFixedRate' and it gave me exact same result. 我尝试使用'scheduleAtFixedRate',它给了我完全相同的结果。 Did I do something wrong? 我做错什么了吗? Or is there some concept I fail to understand? 或者是否有一些我无法理解的概念?

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. 基本上你用简单的英语告诉它“从1秒开始并在那之后每两秒执行一次”所以1,3,5,7等是合乎逻辑的解释。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM