Skip to content

Commit

Permalink
Allow to set a pool interval for SntpClient
Browse files Browse the repository at this point in the history
  • Loading branch information
nikita.pennie committed Oct 7, 2024
1 parent c35a9d6 commit 44751be
Showing 1 changed file with 25 additions and 2 deletions.
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";

/** The default NTP pool interval. By default is set to TIME_UNSET, which means that periodic syncronization is disabled. */
private static final long DEFAULT_POOL_INTERVAL = C.TIME_UNSET;

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

Expand Down Expand Up @@ -88,6 +91,12 @@ public interface InitializationCallback {
@GuardedBy("valueLock")
private static String ntpHost = DEFAULT_NTP_HOST;

@GuardedBy("valueLock")
private static long poolIntervalMs = DEFAULT_POOL_INTERVAL;

@GuardedBy("valueLock")
private static long lastSyncRealtimeMs;

private SntpClient() {}

/** Returns the NTP host address used to retrieve {@link #getElapsedRealtimeOffsetMs()}. */
Expand Down Expand Up @@ -116,6 +125,19 @@ public static void setNtpHost(String ntpHost) {
}
}

/**
* Sets the pool interval.
*
* <p>The default is {@link #DEFAULT_POOL_INTERVAL}.
*
* @param poolIntervalMs The NTP pool interval in milliseconds.
*/
public static void setNtpPoolInterval(long poolIntervalMs) {
synchronized (valueLock) {
SntpClient.poolIntervalMs = poolIntervalMs;
}
}

/**
* Returns whether the device time offset has already been loaded.
*
Expand All @@ -124,7 +146,7 @@ public static void setNtpHost(String ntpHost) {
*/
public static boolean isInitialized() {
synchronized (valueLock) {
return isInitialized;
return isInitialized && (SntpClient.poolIntervalMs == DEFAULT_POOL_INTERVAL || (SystemClock.elapsedRealtime() - lastSyncRealtimeMs < SntpClient.poolIntervalMs));
}
}

Expand Down Expand Up @@ -293,12 +315,13 @@ public void load() throws IOException {
// Synchronized to prevent redundant parallel requests.
synchronized (loaderLock) {
synchronized (valueLock) {
if (isInitialized) {
if (isInitialized && (SntpClient.poolIntervalMs == DEFAULT_POOL_INTERVAL || (SystemClock.elapsedRealtime() - lastSyncRealtimeMs < SntpClient.poolIntervalMs))) {
return;
}
}
long offsetMs = loadNtpTimeOffsetMs();
synchronized (valueLock) {
lastSyncRealtimeMs = SystemClock.elapsedRealtime();
elapsedRealtimeOffsetMs = offsetMs;
isInitialized = true;
}
Expand Down

0 comments on commit 44751be

Please sign in to comment.