-
Timer
Hi All,
I have a program in java which is running already for some time... It is used for logging variables from a PLC. The program is running on Win XP.
For some PLC items I use timers to log them periodically.
Snippets from the code
import java.util.Timer;
import java.util.TimerTask;
public class blabla {........
static Timer timerT10s;
upon initialisation
if (grpT10s != null) {
if (timerT10s != null) {
timerT10s.cancel();
}
Timer timerT10s = new Timer ( ) ;
timerT10s.scheduleAtFixedRate ( new TimerTaskT10s ( ), 250 ,10000 ) ;
}
and timertask
class TimerTaskT10s extends TimerTask {
public void run ( ) {
.....
}
All works quite ok.
Now we found that whenever we change the clock in win XP problems start happening with the timers.
(A) If I set the clock one hour later, I see the application is hogging the CPU up to 100% cpu load.
(B) If I change the clock to one hour earlier, the CPU load is 0% for the application and if I set a breakpoint in my timertaskT10S, there is no stop on the breakpoint.
It looks to me that in situation (A) the timers will callback faster and in situation (B) the timers not callback at all.
I have searched for this, but cannot find information on it.
Is this a common problem with the timers in Java ?
Can something be done about it ? (and yes I must be able to change the clock)
Any suggestions are welcome
-
perhaps don't use Timer? make your own thread that would look like
while(true) {
Thread.sleep(aWhile);
doStuff();
}
-
For the longer timers I can imagine that it works. However I also have timers 10ms and 100ms and they are short for a purpose. It is why I use executeAtFixedRate.... a sleep I think will never be accurate
-
As far as I know, the Java timer classes are based on Thread.sleep... so it will most likely not make much of a difference.
-
what you can do to achieve a bit better accuracy is like
while (currentTime < targetTime) {
Thread.sleep (0.9 of the remaining time);
}