Skip to content

Commit

Permalink
SntpClient periodically re-syncs the offset to NTP server
Browse files Browse the repository at this point in the history
Many of the Android TV platforms do not report accurate `SystemClock.elapsedRealtime()`
In addition this drift is not consistant accross multiple boxes, so the time offset
between any pair of boxes will vary over time.

This variance will lead to a drift in the Live Offset calculation.

Fix is simple, inValidate the NTP server query after a period of time (10 minutes)
and re-issue the call
  • Loading branch information
stevemayhew authored and marcbaechinger committed Oct 14, 2024
1 parent 1084c9e commit 621a9ae
Showing 1 changed file with 12 additions and 0 deletions.
Original file line number Diff line number Diff line change
Expand Up @@ -49,6 +49,9 @@ public final class SntpClient {
/** The default maximum time, in milliseconds, to wait for the SNTP request to complete. */
public static final int DEFAULT_TIMEOUT_MS = 1_000;

/** Max time to allow before re-initializing with NTP server, default is 10 minutes */
private static final long MAX_ELAPSED_MS_TILL_UPDATE = 60 * 10 * 1_000L;

/** Callback for calls to {@link #initialize(Loader, InitializationCallback)}. */
public interface InitializationCallback {

Expand Down Expand Up @@ -96,6 +99,9 @@ public interface InitializationCallback {
@GuardedBy("valueLock")
private static int timeoutMs = DEFAULT_TIMEOUT_MS;

@GuardedBy("valueLock")
private static long lastUpdateElapsedRealtime = C.TIME_UNSET;

private SntpClient() {}

/** Returns the NTP host address used to retrieve {@link #getElapsedRealtimeOffsetMs()}. */
Expand All @@ -120,6 +126,7 @@ public static void setNtpHost(String ntpHost) {
if (!SntpClient.ntpHost.equals(ntpHost)) {
SntpClient.ntpHost = ntpHost;
isInitialized = false;
lastUpdateElapsedRealtime = C.TIME_UNSET;
}
}
}
Expand Down Expand Up @@ -156,6 +163,10 @@ public static void setTimeoutMs(int timeoutMs) {
*/
public static boolean isInitialized() {
synchronized (valueLock) {
if (lastUpdateElapsedRealtime != C.TIME_UNSET) {
long deltaLastUpdate = SystemClock.elapsedRealtime() - lastUpdateElapsedRealtime;
isInitialized = isInitialized && deltaLastUpdate < MAX_ELAPSED_MS_TILL_UPDATE;
}
return isInitialized;
}
}
Expand Down Expand Up @@ -353,6 +364,7 @@ public void load() throws IOException {
}
long offsetMs = loadNtpTimeOffsetMs();
synchronized (valueLock) {
lastUpdateElapsedRealtime = SystemClock.elapsedRealtime();
elapsedRealtimeOffsetMs = offsetMs;
isInitialized = true;
}
Expand Down

0 comments on commit 621a9ae

Please sign in to comment.