简体   繁体   中英

Multithreading - DispatchQueue asyncAfter delay in Swift

I am using the following code to invoke a function periodically every second. The problem is delay is actually 1.1 seconds and gets drifted more and more eventually as can be seen in NSLogs (and it is visible in other parts of the code as well apart from NSLog). Am I doing it wrong, or should I be using timer?

private func updateTimeCode() {
    NSLog("Updating time")
    //Some more code that doesn't take time
    DispatchQueue.main.asyncAfter(deadline: DispatchTime.now() + 1.0) {
        [weak self] in
            self ? .updateTimeCode()
    }
}
  019-08-06 17:15:19.713234+0530 MyApp-Swift[8299:2685215] Updating time 2019-08-06 17:15:20.812652+0530 MyApp-Swift[8299:2685215] Updating time 2019-08-06 17:15:21.913188+0530 MyApp-Swift[8299:2685215] Updating time 2019-08-06 17:15:23.028814+0530 MyApp-Swift[8299:2685215] Updating time 

It's because of the part that you say some more code not relevant taking time. They take time and time passes between each invocation of asyncAfter so basically .now() becomes something more than exactly 1 second ago.

Anyway, it's not a conventional way to achieve it. You need to use timer for that purpose. Here's a useful tutorial about how to use it. Timer in Swift

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM