Background Timers and Swift

One of the issues that I had been having with the Around The Clock appliation was that I was having difficulty with the timer threads when the application was running in the background on macOS.

The use of the traditional scheduled timer causes accuracy issues when the application goes into the background, the timer thread requires a run loop that is active, and when the thrads is in a background queue, this is not always the case. This would cause timer to not execute when they should, which, for a timing application, is an issue.

To find a solution to this, I had to find a timer that would be friendly with queues, so I looked into Grand Central Dispatch (GCD). The DispatchSourceTimer allows for a repeating timer that would fire events on a background queue.

let repeating_timer = RepeatingTimer(timeInterval: 1)
    t.eventHandler = {
        self.runAlarm(alarm_obj: alarm_obj, timer: t)
    }
    repeating_timer.resume()

This is a great blog post by Daniel Galasko describing the implementation of a GCD timer and its follies.