在 Swift 中,对于控制外部硬件的精确时钟,最好的解决方案是什么?我需要编写一个能够以每秒设定的速率(数百或数千赫兹)可靠且高精度地触发的循环函数。
最佳答案
您可以定义一个 GCD 计时器属性(因为与 NSTimer
/Timer
不同,您必须维护自己对 GCD 计时器的强引用):
var timer: DispatchSourceTimer!
然后使用 makeTimerSource(flags:queue:)
创建一个计时器(可能是一个 .strict
计时器,它不受合并、应用程序小睡等的影响,需要注意电源/电池/等的影响) :
let queue = DispatchQueue(label: "com.domain.app.timer", qos: .userInteractive)
timer = DispatchSource.makeTimerSource(flags: .strict, queue: queue)
timer.scheduleRepeating(deadline: .now(), interval: 0.0001, leeway: .nanoseconds(0))
timer.setEventHandler {
// do something
}
timer.resume()
请注意,您应该优雅地处理计时器无法处理您正在寻找的精度的情况。正如 documentation 所说:
Note that some latency is to be expected for all timers, even when a leeway value of zero is specified.
关于ios - Swift 中的高精度定时器,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/43746336/