What should Timertask.scheduleAtFixedRate do if the clock changes?

We want to run the task every 1000 seconds (say).

So we have

timer.scheduleAtFixedRate(task, delay, interval); 

It basically works great. However, this is an embedded system, and the user can change the real-time clock. If they set it to a time in the past after we set the timer, it seems that the timer does not run until the original date / time in real time. Therefore, if they return it for 3 days, the timer will not be executed for 3 days: (

Is this a valid behavior or bug in the Java library? Oracle javadocs does not seem to say anything about dependency or not about the underlying value of the system clock.

If this is permissible, how can we detect this clock change and reschedule our timers?

+4
java clock timertask
source share
2 answers

Looking at the Timer source for Java 1.7, it seems like it uses System.currentTimeMillis() to determine the next execution of the task.

However, looking at the source of ScheduledThreadPoolExecutor , it uses System.nanoTime() .

This means that you will not see this behavior if you use it instead of Timer . To create one, use, for example, Executors.newScheduledThreadPool() .

Why don't you see this behavior due to what doc says for System.nanoTime() :

This method can only be used to measure elapsed time and is not related to any other concept of system or wall time. The return value is nanoseconds from some fixed but arbitrary start time [emphasis mine].

As to whether this is a mistake in Timer, perhaps ...

Note that unlike ScheduledExecutorService , a Timer supports absolute time, and perhaps this explains its use of System.currentTimeMillis() ; In addition, Timer exists since Java 1.3, and System.nanoTime() only appears in 1.5.

But the consequence of using System.currentTimeMillis() is that Timer sensitive to system date / time ... And this is not described in javadoc.

+11
source share

It is reported here http://bugs.sun.com/view_bug.do?bug_id=4290274

Similarly, when the system clock is set to a later time, the task can be performed several times without any delay in order to โ€œcatch upโ€ with the missed performances. This exactly happens when the computer is set to standby / hibernation and the application resumes (as I found out).

This behavior can also be seen in the Java debugger, pausing the timer thread and resuming it.

+3
source share

All Articles