NSTimer continue during sleep mode

Deadly 提交于 2019-12-12 14:01:06

问题


I have a timer app which uses a NSTimer to track minutes. How can I keep the timer going, even when the device is put into sleep mode? Thanks!


回答1:


Adjust After Wake Notification

Scheduled NSTimer instances will halt during sleep. Your application needs to respond to the NSWorkspace's wake notification and adjust its timers.

If you do not respond to wake notifications, your timers will resume but without accounting for the time spent asleep.

See Apple's technical note QA1340 Registering and unregistering for sleep and wake notifications for getting the appropriate notifications.

Example

Consider this situation:

  • Create a timer to trigger in 5 minutes
  • Wait 1 minute
  • Put the computer to sleep for an hour
  • Wake the computer
  • The timer resumes upon waking
  • The timer triggers 4 minutes after waking

From the timer's perspective, five minutes has passed by. Note the language used by NSTimer, it uses relative durations rather than absolute times, scheduledTimerWithTimeInterval:invocation:repeats:.




回答2:


Take a look at this class, which handles sleep/wake for you with the "Hourglass" behavior: https://github.com/jmah/MyLilTimer



来源:https://stackoverflow.com/questions/20176980/nstimer-continue-during-sleep-mode

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!