简体   繁体   中英

Should I invalidate timer when my application is suspended or in background?

I have scheduler that fetch user profile data every 15 seconds.

class ProfileScheduler: NSObject {

    private var _timer: Timer?

    func start() {
        _timer = Timer.scheduledTimer(timeInterval: 15, target: self, selector: #selector(self.fetchProfile), userInfo: nil, repeats: true)
    }

    func fetchProfile() {
       print("Update........")
       ProfileManager.getProfileData()
    }

}

Should I invalidate Timer each time my application in (Suspended, Background) mode? And restore it when app become (Active) .

Should I invalidate Timer each time my application in (Suspended, Background) mode?

Yes. See What to do When Your App is Interrupted Temporarily , which explains that you should stop timers and other periodic tasks. Timers need an active run loop to work, so you should stop any timers when your app becomes inactive, and then restart them when it becomes active again.

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