简体   繁体   English

java.util.Timer无法正常工作

[英]java.util.Timer not working properly

I'm working on a school project and I'm having some issues with the Timer Schedule. 我正在做一个学校项目,但计时器时间表出现了一些问题。 I start the schedule with a 20 sec countdown. 我以20秒的倒计时开始了时间表。 Before starting the schedule I print a text with the current date of the system. 在开始计划之前,我用系统的当前日期打印文本。 Than, after the 20 sec ends, I print the current date and time of the system again. 然后,在20秒结束后,我再次打印系统的当前日期和时间。 The problem is that, instead of having a 20 sec delay between both dates, it takes around 2 minutes to print the second message. 问题在于,这两个日期之间没有延迟20秒,而是需要大约2分钟才能打印第二条消息。 I don't know what is wrong. 我不知道怎么了

Code below: 代码如下:

...
System.out.println(date);
timer = new Timer();
try {
    timer.schedule(new TimerTask() {
        @Override
        public void run() {
            date = new Date();
            System.out.println(date);
        }
        }, 20 * 1000);
} catch (Throwable e) {
    e.printStackTrace();
}    
...

These code is executed by many threads (Some of them get it right, but on others I get this 2 minutes gap). 这些代码由许多线程执行(其中一些线程正确执行,但在另一些线程上则有2分钟的间隔)。

You need to pass delay as 0 in timer.schedule(TimerTask task, long delay, long period) Since you pass only two parameters it tool 20*1000 as period and not delay. 您需要在timer.schedule(TimerTask task, long delay, long period)中将延迟传递为0 ,因为仅传递了两个参数,所以它将20 * 1000作为周期而不是延迟。 Not sure if this helps 不确定这是否有帮助

Output 产量

Wed Jan 21 17:16:47 IST 2015
Wed Jan 21 17:16:47 IST 2015
Wed Jan 21 17:17:07 IST 2015
Wed Jan 21 17:17:27 IST 2015
Wed Jan 21 17:17:47 IST 2015
Wed Jan 21 17:18:07 IST 2015
Wed Jan 21 17:18:27 IST 2015
Wed Jan 21 17:18:47 IST 2015

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

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