How to Move Timer to Background Thread

user3185748 picture user3185748 · Jan 8, 2015 · Viewed 11.3k times · Source

I currently have two NSTimer timers in my app that are responsible for taking data and updating the UI. I have noticed recently that while the timers are running I have poor UI performance, for example the user can't scroll through my UITableview well or at all. I've read elsewhere that it is possible to push the timers into a different runloop and that this could help. This is what my timer looks like now:

let aSelector : Selector = "updateLocation"
timer = NSTimer.scheduledTimerWithTimeInterval(((NSUserDefaults.standardUserDefaults().stringForKey("mapUpdate")! as NSString).doubleValue), target: self, selector: aSelector, userInfo: nil, repeats: true)

How can I modify my Swift timer such that it runs in a background thread? I've been reading about it but have been getting confused.

Answer

Amirreza picture Amirreza · Sep 8, 2018

If a timer is fired on the main thread's run loop, you will probably have a problem with either the timer function or UI operation.

For example, suppose you have triggered a timer. There is also a tableView in your app that shows a list to the user and the user is scrolling the table. Meanwhile, the timer's time elapses. We expect that the code block of the timer executes immediately, but it doesn't until the user ends the scroll operation. In many cases, this isn't what we want.

The source of this problem and the problem you mentioned in your question is the fact that you have run the timer on the main thread, where your task and all UI operations are handled serially. serial means one task is executed only if the previous task finished.

To solve that, one solution is to call timers on a background thread's run loop like below:

DispatchQueue.global(qos: .background).async {
        Timer.scheduledTimer(withTimeInterval: 3, repeats: false) { _ in
            print("After 3 seconds in the background")
        }
        RunLoop.current.run()
    }

The scheduledTimer method creates a timer and schedules it on the current run loop. The following code has the same meaning:

DispatchQueue.global(qos: .background).async {
        let timer = Timer(timeInterval: 6, repeats: false) { _ in
            print("After 6 seconds in the background")
        }
        let runLoop = RunLoop.current
        runLoop.add(timer, forMode: .default)
        runLoop.run()
    }

Notice: if your timer is called repeatedly, don't forget to call invalidate() of the timer at the end of the task, otherwise the run loop will keep a strong reference to the target object of the timer that could result in memory leak.

There is also a better option instead of the Timer class. You can use DispatchSourceTimer.

For more info refer to the following links: