Java timing, System.nanoTime() is better than System.currentTimeMillis(), but will it last sleep?
I’m trying to implement a timer that can be used for short (seconds) events or longer (hours, etc.) events.
Ideally, it should persist for periods of CPU shutdown, for example, when the battery dies. If I set the start time using System.currentTimeMillis() and set the end time with the same function, it works in almost all cases, except for leap seconds, leap years, daylight saving time changes, etc. periods… Or, if the user just changes the time (I’ve verified this). By the way, this is on Android.
Conversely, if I use System.nanoTime(), in addition to being probably more accurate, it doesn’t have the usual “hard times” issues like time changes. My question is, System.nanoTime() measures nanoseconds from any time in “hard times”? I’m not sure what the correct term is, but for example, System.nanoTime() runs at X, then after X+1 hour, the system shuts down (e.g. the battery on the Android device is dead), then X+10 hours, the system boots, at which point running System.nanoTime() returns 10 hours? Or does it return 1 hour (because the “counter” used by nanoTime may not be running when the system shuts down/hibernate?). )。
android.os.SystemClock.elapsedRealtime() – The number of milliseconds since the system started, including the time in the sleep state. This should be your best bet.
I don’t think you can measure off time in android.
For more information, it is best to check the Android system clock page. http://developer.android.com/reference/android/os/SystemClock.html