Search code examples
swifttimerbackground-thread

How to execute a method every second on a background thread so it doesn't affect the performance of the app


I am trying to access my database every 30 seconds, however, whenever the method executes I can clearly see a performance dip in the application.

So far this is my current code:

var timer = Timer()

override func viewDidLoad() {
    super.viewDidLoad()
    scheduledTimerWithTimeInterval()

}

func scheduledTimerWithTimeInterval(){
    timer = Timer.scheduledTimer(timeInterval: 30, target: self, selector: #selector(self.updateCounting), userInfo: nil, repeats: true)
}

@objc func updateCounting(){
    getDatabaseInfo()
}

I am trying to do the same thing, except I would like to execute the getDatabaseInfo() method on a background thread so that the app's performance is not compromised.


Solution

  • Use Grand Central Dispatch :

    DispatchQueue.global(qos: .background).async {
        getDatabaseInfo()
    }