TrueTime Android

repository·master·Indexed 23 days ago

https://github.com/instacart/truetime-android

An Android library for accurate time synchronization using the Network Time Protocol (NTP) to mitigate issues caused by local device clock manipulation. It provides tools for calculating network delay and clock offset via SntpResult, a background synchronization loop via sync(), and flexible time retrieval methods including now(), nowSafely(), and nowTrueOnly().

Tokens
1.1K
Snippets
0
Records
8
Agent score
81%

What's inside truetime-android

  1. Understand strictNtpMode behavior

    master

    The strictNtpMode setting controls how aggressively the library attempts to verify time accuracy:

    • When true (Default): The library follows a strict SNTP call sequence. It resolves the NTP pool to multiple IP addresses and performs multiple calls to each. If a call fails, it will retry up to retryCountAgainstSingleIp times per IP.
    • When false: The library ignores the strict sequence and returns as soon as it receives at least one successful SNTP call. This is more permissive and similar to many other common NTP libraries.
  2. Use BasicCacheProvider for NTP result caching

    master

    The BasicCacheProvider is an implementation of the CacheProvider interface used to store and manage SntpResult objects. It maintains a small, fixed-size stack (up to 3 entries) of the most recent NTP results. When the capacity is reached, it evicts the oldest entry to make room for the newest.

    Key behaviors:

    • insert(result): Adds a new SntpResult. If the stack is full, it removes the oldest entry.
    • fetchLatest(): Returns the most recent SntpResult or null if the cache is empty.
    • fetchAll(): Returns an iterable of all stored SntpResult objects.
    • hasAnyEntries(): Returns true if the cache contains any results.
    • invalidate(): Clears all entries from the cache.
  3. Start the TrueTime synchronization loop with sync()

    master

    To keep the TrueTime offset updated, you must start the background synchronization process by calling sync(). This returns a Kotlin Coroutine Job that manages a continuous loop of synchronization attempts based on the configured syncInterval.

    When sync() is called, the library will:

    1. Attempt to initialize the NTP connection.
    2. If successful, update the internal TimeKeeper.
    3. Wait for the duration specified in params.syncInterval.
    4. Repeat the process.

    If initialization fails, the error is reported via the TrueTimeEventListener.

  4. Monitor TrueTime synchronization with TrueTimeEventListener

    master

    You can provide a TrueTimeEventListener during the initialization of TrueTimeImpl to react to the lifecycle of the NTP synchronization process. This is useful for UI updates or error logging.

    Key events you can listen for include:

    • initialize(params): Called when synchronization starts.
    • initializeSuccess(ntpResult): Called when a successful NTP sync occurs.
    • initializeFailed(exception): Called when the initial synchronization attempt fails.
    • sntpRequestFailed(exception): Called when an individual SNTP request fails.
    • syncDispatcherException(throwable): Called when an unhandled exception occurs within the synchronization coroutine scope.
  5. Calculate time metrics with SntpResult

    master

    The SntpResult class provides methods to extract synchronization metrics from an SNTP request. It uses an internal ntpResult array to calculate the network delay, clock offset, and the estimated 'true time'.

    Key methods:

    • roundTripDelay(): Returns the round-trip delay (δ) in milliseconds.
    • clockOffset(): Returns the clock offset (θ) in milliseconds.
    • trueTime(): Returns the estimated 'true time' (the actual time when the NTP call was made) by combining the response time and the clock offset.
    • timeSinceBoot(): Returns the milliseconds since boot (including time spent in sleep) at the time the NTP call was made.
  6. Get the current TrueTime with now(), nowSafely(), and nowTrueOnly()

    master

    The TrueTime interface provides three ways to retrieve the current time, depending on whether you want to allow fallback to the local system clock when the NTP synchronization is unavailable.

    • now(): Returns the current time. Its behavior depends on the returnSafelyWhenUninitialized configuration parameter. If true, it falls back to the local clock if TrueTime is not yet synchronized; otherwise, it only returns the TrueTime.
    • nowSafely(): Always returns the best available time, falling back to the local system clock if TrueTime synchronization has failed or is not yet initialized.
    • nowTrueOnly(): Returns only the time synchronized via NTP. If synchronization is unavailable, this will not return a valid TrueTime.
    • hasTheTime(): Returns true if the library has successfully synchronized with an NTP server and has a valid time offset.