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.
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!
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.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With