Kronos 是一个用 Swift 编写的 NTP 客户端库。它支持亚秒级精度,并提供一个稳定的单调时钟,该时钟不会受到时钟更改的影响。

示例应用

这里 是一个示例应用,它在左侧显示单调的 Clock.now,在右侧显示系统时钟(最初是过时的)。

ascii-clock

用法

使用 NTP 服务器池同步时钟

调用 Clock.sync 将向给定 NTP 池中的最多 5 个服务器发送一批 NTP 请求(默认为 time.apple.com)。一旦我们收到第一个响应,就会调用给定的闭包,但 Clock 将继续尝试获取更准确的响应。

Clock.sync { date, offset in
    // This is the first sync (note that this is the fastest but not the
    // most accurate run
    print(date)
}

获取 NTP 同步的日期

Clock.now 是一个单调的 NSDate,不会受到时钟更改的影响。

NSTimer.scheduledTimerWithTimeInterval(1.0, target: self,
                                       selector: #selector(Example.tick),
                                       userInfo: nil, repeats: true)

@objc func tick() {
    print(Clock.now) // Note that this clock will get more accurate as
                     // more NTP servers respond.
}

安装

CocoaPods

将 Kronos 添加到您的 Podfile

pod 'Kronos'

Swift Package Manager

将 Kronos 添加到您的 Package.swift

.package(name: "Kronos", url: "https://github.com/MobileNativeFoundation/Kronos.git", .upToNextMajor(from: "TAG")),

Bazel

将 Kronos 添加到您的 WORKSPACE

http_archive(
    name = "Kronos",
    sha256 = "",
    strip_prefix = "Kronos-TAG/",
    url = "https://github.com/MobileNativeFoundation/Kronos/archive/TAG.tar.gz",
)

然后依赖于 @Kronos//:Kronos

Android

请查看 Kronos for Android