0

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()
    }
Brunni
  • 143
  • 1
  • 11
  • iOS doesn't give apps that entered background execution time, except for some specific time-sensitives tasks ([link](https://developer.apple.com/documentation/uikit/app_and_environment/scenes/preparing_your_ui_to_run_in_the_background), [link](https://developer.apple.com/documentation/uikit/app_and_environment/scenes/preparing_your_ui_to_run_in_the_background/updating_your_app_with_background_app_refresh)). You have to design your app in such a way as to assume that your app won't continue running (e.g. by calculating the time difference when it was in background) – New Dev May 30 '21 at 14:53
  • Sorry I should have been clearer, it's for macOS. The OS is able to run stuff in the background (e.g. if I make a command line tool), but I'm not sure if it's totally impossible with a normal Swift app? – Brunni May 30 '21 at 14:59
  • 1
    Check this: https://stackoverflow.com/a/62360516/1187415 – Martin R May 30 '21 at 16:58
  • Thank you so much Martin! That was it. How do I mark it as the answer? – Brunni May 31 '21 at 13:44

0 Answers0