简体   繁体   中英

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. 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. The problem is that, instead of having a 20 sec delay between both dates, it takes around 2 minutes to print the second message. 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).

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. 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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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