【问题标题】:How to get the time in sync with macOS system clock when using a timer to update the time?使用计时器更新时间时如何使时间与 macOS 系统时钟同步?
【发布时间】:2021-04-07 05:34:17
【问题描述】:

我正在使用此代码在 NSLabel 中显示时间:

型号

func startClock() {
    timer = Timer(timeInterval: 1.0, target: self, selector: #selector(fireAction), userInfo: nil, repeats: true)
    RunLoop.current.add(timer!, forMode: RunLoop.Mode.common)
    timer?.tolerance = 0.05
    fireAction()
}

@objc dynamic func fireAction() {
    delegate?.timeToUpdateClock(self)
}

视图控制器

extension ViewController: ClockWorksProtocol {
    func timeToUpdateClock(_ timer: ClockWorks) {
        tick()
     }
}

 func tick() {
    clockDateLabel.stringValue = DateFormatter.localizedString(from: Date(), dateStyle: .full, timeStyle: .none)
    clockTimeLabel.stringValue = DateFormatter.localizedString(from: Date(), dateStyle: .none, timeStyle: .medium)
}

一切似乎都运行良好,但不幸的是,显示的秒数与您在菜单栏上的时钟中看到的秒数不同步。我认为会发生这种情况,因为我每秒都会更新时钟,但用户不会在第二秒正确开始时单击,而是在从一秒到下一秒的随意间隔内(我使用 timeInterval 作为 1.0 的计时器) .

我可以将计时器的 timeInterval 从 1.0 秒更改为 0.1 秒。这似乎可行,但我担心这可能会消耗太多资源。

我发布了两个同时制作的屏幕截图。它们显示两个不同的时间(秒):

我该如何弥补差距?

【问题讨论】:

  • 在什么意义上不同步? Date() 时钟上的时间。现在,简单明了。
  • 我很马特,我编辑了问题以使其更清楚。谢谢。
  • 不要盲目地重复计时器,而是看看现在是什么时间,并设置一个间隔以在下一秒开始时触发一次。
  • 嗨,马特,感谢您提供有用的评论,您是否愿意创建一个答案让我无法接受?如果您还可以添加一个示例来阐明您建议的技术。

标签: swift macos timer clock


【解决方案1】:

我知道您可以在这里采取两种方法:

  1. 计算dt 从现在到下一秒之间的时间量。
let nextSecond = floor(now.timeIntervalSince1970) + 1
let dt = nextSecond - now.timeIntervalSince1970

制作一个从现在开始精确触发一次dt 的计时器。在该计时器的回调中,启动一个以 1 秒为间隔重复的计时器(每次执行 tick()),这正是您的 startClock() 函数所做的。

如果您希望滴答声尽快开始,您也可以在第一个计时器触发时运行 tick()


  1. 将下一秒发生的时刻确定为日期。

Date(timeIntervalSince1970: floor(Date().timeIntervalSince1970) + 1)

将此初始化用于计时器,该计时器在特定的fireAt 日期启动它,并将其设置为每秒重复一次。

let timer = Timer(fireAt: 
                      Date(timeIntervalSince1970:
                               floor(Date().timeIntervalSince1970) + 1),
                  interval: 1.0,
                  target: self,
                  selector: #selector(fireAction),
                  userInfo: nil, 
                  repeats: true)

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2018-11-15
    • 1970-01-01
    • 2019-08-10
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多