Saturday, December 21, 2024
HomeiOS Developmentios - How you can name Swift operate at specified date/time

ios – How you can name Swift operate at specified date/time

[ad_1]

If you happen to make a GCD timer with makeTimerSource with a flag of .strict, it’ll choose out of timer coalescing:

The system makes its greatest effort to look at the timer’s specified leeway worth, 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: .foremost)
    timer?.setEventHandler(handler: block)
    timer?.schedule(deadline: .now() + interval, leeway: .milliseconds(500))
    timer?.activate()
}

After which:

startTimer(in: .seconds(240)) { [weak self] in
    self?.foo()
}

Be aware, in contrast to a Timer, which is retained by the RunLoop upon which you schedule it, it’s a must to maintain your personal sturdy reference to the GCD timer, as proven above. You may make Timer properties weak (in order that they’re deallocated when the RunLoop releases them), however you need sturdy references to GCD timers.

Just a few caveats:

  • Be aware using [weak self] seize record. You usually wish to keep away from sturdy reference cycle (particularly if the timer was a repeating timer).

  • This sample needs to be employed solely when completely wanted, as you might be opting out of the facility saving options provided by timer coalescing. I’d count on that that is extra energy environment friendly than the repeating timer method, 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 is just not blocked. Clearly, we by no means block the primary thread, however you may 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 operating. If the app is suspended, timers can’t hearth. If you’d like the person to be notified on the appointed time even when the app is just not at the moment operating, you’d use a regionally scheduled person notification.

[ad_2]

RELATED ARTICLES

LEAVE A REPLY

Please enter your comment!
Please enter your name here

Most Popular

Recent Comments