Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Stable timer independent of system time

Tags:

java

timer

I use java.util.Timer to trigger jobs in my app, but I found that it is depend on system time: if system time is adjusted, timer's trigger will be affected.

For example, if system time goes back by 80 seconds, the timer will stop working for 80 seconds.

Java has a System.nanoTime method which is independent of system time, but it seems that it cannot be used in Timer.

Is there Timer library that supports what I need? Or I have to implement it myself?

Notice that I don't need a precise current time(date), I need a precise time interval

like image 996
jean Avatar asked Dec 24 '11 09:12

jean


1 Answers

you have 2 options:

  • Write your one timer, relatively trivial. Before anyone tell reinvent the wheel, being able to carry the task yourself is always important. Especially when it's around 20 lines of code.
  • Use java.util.concurrent.ScheduledThreadPoolExecturor and use scheduleAtFixedRate, the queue impl. is based on System.nanoTime.
  • Install ntp daemon that adjusts the time by tuning (slowing down, speeding up) the system clock in very slight fashion during long time span.

Few other things, perfect 100ms is a tall order in non-real time GC environment as GC may STW (stop the world) for seconds sometimes. Sun's GCs can't do that super reliably. IBM's Metronome running on modified Linux kernel is supposed to be able to. You may wish to pay attention to if your application is truly real-time demanding.

like image 126
3 revs Avatar answered Sep 22 '22 02:09

3 revs