swift - 计时器不会在 WatchKit 上每秒触发一次

标签 swift timer watchkit

这个计时器不是每秒触发一次,当我检查日志和 UI 时,它似乎每 3-4 秒触发一次。

func startTimer() {
    print("start timer")
    timer = Timer.scheduledTimer(timeInterval: 1,
                                 target: self,
                                 selector: #selector(timerDidFire),
                                 userInfo: nil,
                                 repeats: true)
}

func timerDidFire(timer: Timer) {
    print("timer")
    updateLabels()
}

这只是由于功能不足而在 Watch 上发生的事情,还是我的代码有问题?

如果需要,这里是日志:

0.0396000146865845
3.99404102563858
7.97501903772354
11.9065310359001

编辑:

澄清一下,我每秒更新的是锻炼计时器,因此它需要每秒更新一次。

最佳答案

如果您的应用正忙于做其他事情,这会阻止或延迟运行循环检查触发时间是否已重复过去,the timer will only fire once during that period :

A repeating timer always schedules itself based on the scheduled firing time, as opposed to the actual firing time. For example, if a timer is scheduled to fire at a particular time and every 5 seconds after that, the scheduled firing time will always fall on the original 5 second time intervals, even if the actual firing time gets delayed. If the firing time is delayed so far that it passes one or more of the scheduled firing times, the timer is fired only once for that time period; the timer is then rescheduled, after firing, for the next scheduled firing time in the future.

顺便说一句,根据对更改的响应(例如,观察)或对事件的 react (例如,完成处理程序)来更新您的 UI 可能会更有效。

  • 如果在计时器间隔期间没有任何更改,这可以避免在驱动检查但实际上没有要执行的 UI 更新时为应用创建繁忙的工作。

  • 它还可以防止触发间隔内的多次更改被忽略,因为计时器驱动的模式只会在 UI 中显示最后一次更改。

关于swift - 计时器不会在 WatchKit 上每秒触发一次,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/38937786/

相关文章:

c# - 创建计时器并启动它并随时获取它的值 c#

ios - 使用 updateApplicationContext 发送钥匙串(keychain)值是否安全

ios - Watchkit 扩展中的 SwiftyJSON 不起作用

c - STM32多 channel 输入捕获在所有 channel 上过度捕获(中断未执行)

ios - 如何使用动画以编程方式隐藏和显示 WKInterfaceGroup?

ios - Swift,当 Core Animation 完成时

ios - 什么是正确的长度 : argument to provide to NSRange for NSRegularExpression using a (Swift) String?

swift - 在 ARKIt 中使用 SCNFloor

ios - 如何在 Swift 中验证澳大利亚电话号码?

c# - 在本地运行一次计时器触发的 Azure 函数的最简单方法是什么?