For high precision, steady timer, I like to use the DispatchSource API.
I use it for precision clocking, or when I need a timer to run during a control drag.
There is certainly other smarter ways to update the UI.
The leeway also has a minimal value, check the 'DispatchSourceTimer' documentation for all details.
let queue = DispatchQueue(label: "com.myCompany.myApp.timerQueue",
qos: .userInteractive,
attributes: [],
autoreleaseFrequency: .inherit,
target: nil)
let timer = DispatchSource.makeTimerSource(flags: .strict, queue: queue)
var counter: Int = 0
timer.schedule(deadline: DispatchTime.now(),
repeating: DispatchTimeInterval.nanoseconds(periodInNanoseconds),
leeway: DispatchTimeInterval.nanoseconds(1))
timer.setEventHandler {
// Do something at high rate in the queue
counter+=1
if counter % 10000 == 0 {
DispatchQueue.main.async {
// Do something in the main queue ( UI Update )
}
}
}
timer.resume()
Topic:
App & System Services
SubTopic:
Processes & Concurrency
Tags: