Java timing, System.nanoTime() batter than System.currentTimeMillis() but does it persist over sleep?

StackOverflow https://stackoverflow.com/questions/11091824

Question

I am trying to implement a timer, it may be used for short (seconds) events, or longer (hours, etc) events.

Ideally it should persist over periods when the CPU is off, for example, battery has died. If I set the start time using System.currentTimeMillis() and end time using the same function, it works in almost all cases, except during periods like leap seconds, leap years, daylight savings time changes, etc... Or, if the user just changes the time (I've verified this). This is on an Android system, btw.

Instead, if I used System.nanoTime(), in addition to potentially being more accurate, it won't have the usual "hard time" issues with time changes, etc. My question is, does System.nanoTime() measure nanoseconds from some arbitrary time, in "hard time"? I'm not sure what the proper term is, but for example, will System.nanoTime() ran at X, then X+1 hour later, the system is shut off (dead battery on Android device, for example), then X+10 hours, the system is started, will running System.nanoTime() at this point return 10 hours? Or will it return 1 hour (since the "counter" that nanoTime uses may not be running when system is off/asleep?).

Was it helpful?

Solution

android.os.SystemClock.elapsedRealtime() - milliseconds since the system was booted including time spent in sleep state. This should be your best bet.

I dont think you can measure the switched off time in android.

For more info it might be better to check android system clock page. http://developer.android.com/reference/android/os/SystemClock.html

OTHER TIPS

It is undefined:

"The value returned represents nanoseconds since some fixed but arbitrary origin time (perhaps in the future, so values may be negative). The same origin is used by all invocations of this method in an instance of a Java virtual machine; other virtual machine instances are likely to use a different origin."

For simplicity, we'll say when you run it at time X, the origin is X (this is allowed). That means it will return 0 then, and within the VM instance, time will then elapse at the same rate as a normal clock.

When you use Thread.sleep, that doesn't change the VM instance, so it isn't treated specially.

However, after the device is rebooted, you're in a different VM instance. Therefore, X is no longer guaranteed to be the origin.

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top