High precision timer in Swift

What would be the best solution in Swift for precision clocks to control external equipment? I need to write a loop function that will fire at a given rate per second (hundreds or thousands of Hz) reliably and with high precision.

+3


source to share


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







All Articles