[ad_1]
Should you make a GCD timer with makeTimerSource with a flag of .strict, it is going to choose out of timer coalescing:
The system makes its finest effort to watch the timer’s specified
leewayworth, even when the worth is smaller than the default leeway.
For instance:
var timer: DispatchSourceTimer?
func startTimer(in interval: DispatchTimeInterval, block: @escaping () -> Void) {
timer = DispatchSource.makeTimerSource(flags: .strict, queue: .predominant)
timer?.setEventHandler(handler: block)
timer?.schedule(deadline: .now() + interval, leeway: .milliseconds(500))
timer?.activate()
}
After which:
startTimer(in: .seconds(240)) {
print("fired", Date())
}
Notice, not like a Timer, which is retained by the RunLoop upon which you schedule it, you need to hold your personal robust reference to the GCD timer, as proven above. You would possibly make Timer properties weak (in order that they’re deallocated when the RunLoop releases them), however you need robust references to GCD timers.
Just a few caveats:
-
This sample ought to be employed solely when completely wanted, as you’re opting out of the facility saving options provided by timer coalescing. I might count on that that is extra energy environment friendly than the repeating timer strategy, however much less energy environment friendly than letting the OS use its discretion to coalesce its timers.
-
This sample assumes that the queue on which it’s scheduled just isn’t blocked. Clearly, we by no means block the primary thread, however you’ll be able to all the time think about using your personal goal queue.
-
For the sake of future readers, this sample clearly applies when the app is definitely working. If the app is suspended, timers can’t fireplace. If you’d like the person to be notified on the appointed time even when the app just isn’t presently working, you’d use a domestically scheduled person notification.
[ad_2]
