Swift中的高精度计时器

Ale*_*der 5 macos timer ios swift

在Swift中使用精确时钟控制外部硬件的最佳解决方案是什么?我需要编写一个循环功能,该功能可以可靠且高精度地以每秒设置的速率(数百或数千赫兹)触发。

Rob*_*Rob 6

您可以定义GCD计时器属性(因为与NSTimer/ 不同Timer,您必须维护自己对GCD计时器的强引用):

var timer: DispatchSourceTimer!
Run Code Online (Sandbox Code Playgroud)

然后使用以下方法制作一个计时器(可能是.strict一个无需进行合并,应用程序午睡等操作的计时器,并且要意识到所涉及的电源/电池/等方面的隐患)makeTimerSource(flags:queue:)

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()
Run Code Online (Sandbox Code Playgroud)

注意,您应该适当地处理计时器无法满足您所寻找精度的情况。如文档所述

请注意,即使将回程值指定为零,所有计时器也会有一些等待时间。