Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

SntpClient periodically re-syncs the offset to NTP server #697

Closed
Closed
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
Original file line number Diff line number Diff line change
Expand Up @@ -43,6 +43,9 @@ public final class SntpClient {
/** The default NTP host address used to retrieve {@link #getElapsedRealtimeOffsetMs()}. */
public static final String DEFAULT_NTP_HOST = "time.android.com";

/** 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 @@ -88,6 +91,9 @@ public interface InitializationCallback {
@GuardedBy("valueLock")
private static String ntpHost = DEFAULT_NTP_HOST;

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

private SntpClient() {}

/** Returns the NTP host address used to retrieve {@link #getElapsedRealtimeOffsetMs()}. */
Expand All @@ -112,6 +118,7 @@ public static void setNtpHost(String ntpHost) {
if (!SntpClient.ntpHost.equals(ntpHost)) {
SntpClient.ntpHost = ntpHost;
isInitialized = false;
lastUpdateElapsedRealtime = C.TIME_UNSET;
}
}
}
Expand All @@ -124,6 +131,10 @@ public static void setNtpHost(String ntpHost) {
*/
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 @@ -299,6 +310,7 @@ public void load() throws IOException {
}
long offsetMs = loadNtpTimeOffsetMs();
synchronized (valueLock) {
lastUpdateElapsedRealtime = SystemClock.elapsedRealtime();
elapsedRealtimeOffsetMs = offsetMs;
isInitialized = true;
}
Expand Down