简体   繁体   中英

Timer in background is very slow

I'm working with timer and I've try to make it works in background. On simulator this works fine but on my device (iOS 11) it's very slow: 1 seconde became 5 or 6 secondes...

This is my code for run application in background:

backgroundTaskIdentifier = UIApplication.shared.beginBackgroundTask(
    expirationHandler:
      {UIApplication.shared.endBackgroundTask(self.backgroundTaskIdentifier!)}
    )

Info.plist: Application does not run in background : NO

How can I make it works?

EDIT:

This is my timer code:

timer = Timer.scheduledTimer(timeInterval: 0.01, target: self, 
  selector:#selector(ViewController.updateTimer), userInfo: nil, repeats: true)

EDIT 2:

func updateTimer () {
    var j = 0
    for _ in rows {
        if (rows[j]["Playing"] as! Bool == true ) {
            rows[j]["time"] = (rows[j]["time"] as! Double + 0.01) as AnyObject
        // print(rows[j]["time"]) - PRINT OUTPUT HERE
            rows[j]["lastTime"] = (rows[j]["lastTime"] as! Double + 0.01) as AnyObject
        }
        if (rows[j]["lastTime"] as! Double > 60.0) {
            min[j] += 1
            rows[j]["lastTime"] = 0.00 as AnyObject
        }
        j += 1
    }
}

Instead of just printing your output, which might be executed from a different thread, print it from the main thread. That's why you might see the delay:

DispatchQueue.main.async {
  print(rows[j]["time"])
}

Your timer interval is too short. Timers have a resolution of 50-100 ms, so your interval (10 ms) can't get executed so fast. I think when your app is in the background this effect increases.

Take a look at this answer: https://stackoverflow.com/a/30983444/5613280

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