For a macOS app (SwiftUI).
I'm setting up a simple timer using DispatchSource.makeTimerSource
as shown below. It runs properly, but when the app is in background (hidden, minimized or not active), after 40 seconds it slows down a lot. Events are still fired, but every tens of seconds instead of 0.5 seconds. Any idea why? And how to make something keep running in the background at a normal interval?
@main
class AppDelegate: NSObject, NSApplicationDelegate {
var bgTimer: DispatchSourceTimer?
var count = 0.0
func applicationDidFinishLaunching(_ aNotification: Notification) {
[…]
let queue = DispatchQueue.global(qos: .background)
bgTimer = DispatchSource.makeTimerSource(flags: [], queue: queue)
bgTimer?.schedule(deadline: DispatchTime.now(), repeating: .milliseconds(500))
bgTimer?.setEventHandler(handler: {
self.count += 0.5
print("completed task from background ", self.count)
})
bgTimer?.resume()
}
}
Thank you in advance :)
[Edit] Threads are also throttled after a little while:
func applicationDidFinishLaunching(_ aNotification: Notification) {
let thread = Thread {
while true {
print("something")
sleep(1)
}
}
thread.start()
}