我有一个精确的计时器,需要每 40 毫秒更新一次(尽可能精确)。在iOS10上它很好(我使用新的scheduleRepeating
方法),但在iOS9上我需要使用旧的方式(scheduledTimer
code>)而且它相当滞后(有时 24ms,有时 72...),所以我的硬件界面和视觉效果也很滞后。
有什么建议吗?
func launchTimer() {
if #available(iOS 10.0, *) {
startTickTimer()
} else {
let timerQueue = DispatchQueue(label: "my.queue.tickTimer", attributes: .concurrent)
self.swiftTimer = Timer.scheduledTimer(timeInterval: period, target: self, selector: #selector(executeTimer), userInfo: nil, repeats: true)
timerQueue.async {
RunLoop.current.add(self.swiftTimer!, forMode: RunLoopMode.defaultRunLoopMode)
}
}
}
static func startTickTimer() {
let queue = DispatchQueue(label: "my.queue.tickTimer", attributes: .concurrent)
DMXTimer.tickTimer?.cancel()
DMXTimer.tickTimer = DispatchSource.makeTimerSource(queue: queue)
DMXTimer.tickTimer?.scheduleRepeating(deadline: .now(), interval: .milliseconds(40), leeway: .seconds(1))
DMXTimer.tickTimer?.setEventHandler {
executeTimer()
}
DMXTimer.tickTimer?.resume()
}
static func executeTimer() {
print("hello moto")
}
最佳答案
来自关于 NSTimer
的 Apple 文档:
A timer is not a real-time mechanism. If a timer’s firing time occurs during a long run loop callout or while the run loop is in a mode that isn't monitoring the timer, the timer doesn't fire until the next time the run loop checks the timer. Therefore, the actual time at which a timer fires can be significantly later. See also Timer Tolerance.
如果你想要一个非常精确的计时器,你可以检查 Apple Tech Note 的实现。并在 Swift 中进行调整或使用 CADisplayLink
进行显示更新。
关于ios - Swift 3 精确定时器重复(iOS 9),我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/44066584/