在Swift中使用精确时钟控制外部硬件的最佳解决方案是什么?我需要编写一个循环功能,该功能可以可靠且高精度地以每秒设置的速率(几百或几千赫兹)触发.
What would be the best solution in Swift for a precise clock to control external hardware? I need to write a loop function that would fire at a set rate per second (hundreds or thousands Hz) reliably and with high precision.
推荐答案您可以定义GCD计时器属性(因为与NSTimer/Timer不同,您必须维护自己对GCD计时器的强烈引用):
You can define a GCD timer property (because unlike NSTimer/Timer, you have to maintain your own strong reference to the GCD timer):
var timer: DispatchSourceTimer!,然后使用.strict计时器,该计时器不受合并,应用程序午睡等影响,并且意识到其中涉及的电源/电池/等方面的隐患)://developer.apple/reference/dispatch/dispatchsource/2300106-maketimersource"rel =" noreferrer> makeTimerSource(flags:queue:) :
And then make a timer (probably a .strict one that is not subject to coalescing, app nap, etc., with awareness of the power/battery/etc. implications that entails) with 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()请注意,您应该适当地处理计时器无法处理您要寻找的精度的情况.正如文档所述:
Note, you should gracefully handle situations where the timer cannot handle the precision you are looking for. As the documentation says:
请注意,即使将回程值指定为零,所有计时器也会有一些等待时间.
Note that some latency is to be expected for all timers, even when a leeway value of zero is specified.
更多推荐
Swift中的高精度计时器
发布评论