High precision timer in Swift
1 answer
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 create a timer (perhaps .strict
one that is not to be bundled, appended, etc., with the awareness of the power / battery / etc impact that it 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()
Please note that you must intelligently handle situations where the timer cannot handle the precision you are looking for. As the documentation says:
Note that all timers need to wait some delay even if the limit is set to zero.
+3
source to share