Below are the two ways i am doing it, but wanted to know which is best way to do it and why
First way
Timer.scheduledTimer(withTimeInterval: 43200, repeats: true) { timer in
let randomNumber = Int.random(in: 1...20)
print("Number: \(randomNumber)")
if randomNumber == 20 {
timer.invalidate()
}
}
second way
let date = Date().addingTimeInterval(43200)
let timer = Timer(fireAt: date, interval: 0, target: self, selector: #selector(runCode), userInfo: nil, repeats: false)
RunLoop.main.add(timer, forMode: .common)
@objc func runCode()
{
print("Running code after every 5 seconds")
}
use
and none of the above mentioned ways.NSBackgroundActivityScheduler
Correct. Doing this with a timer is quite tricky because timers behave strangely when the CPU sleeps. Also, your timer is not coordinated with other maintenance activity.
NSBackgroundActivityScheduler
takes care of all of this for you.
Be aware that part of the
NSBackgroundActivityScheduler
API contract is that it won’t run your code at
exactly the time you request. Rather, it will hit this deadline on average. It’s this flexibility that allows it to coordinate your work with other maintenance work.
Share and Enjoy
—
Quinn “The Eskimo!”
Apple Developer Relations, Developer Technical Support, Core OS/Hardware
let myEmail = "eskimo" + "1" + "@apple.com"