5

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

jean
  • 2,825
  • 2
  • 35
  • 72
  • Since Java 5.0 (2004) you can use ScheduledExecutorService. – Peter Lawrey Dec 24 '11 at 11:13
  • 1
    @PeterLawrey, nanoTime exists since the same release, so the OP should know about ScheduledExecutor. – bestsss Dec 24 '11 at 15:56
  • I used ScheduledExecutoeService, but I am facing problem with 64 bit JVM. Please help http://stackoverflow.com/questions/9044423/java-scheduler-which-is-completely-independent-of-system-time-changes – YoK Jan 30 '12 at 09:05

2 Answers2

6

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.

bestsss
  • 11,796
  • 3
  • 53
  • 63
0

If your computer is isolated and off the Internet i think there is not much you can do if the user tampers with the clock.

On the other hand, if this is not the case, you will find quite many API's and Mashups that will allow you to read the correct time. You could read the time from there. You could read the time from time.gov. Also twinsun.com you give you lots of additional options.

100ms seems like too low for Internet time-access.

Costis Aivalis
  • 13,680
  • 3
  • 46
  • 47
  • Yeah, another solution is let system auto adjust system time in a suitable frequency. If the change range in 1 or 2 seconds, that can be accept. But that is not prefect way. – jean Dec 24 '11 at 10:00