深度睡眠后,后台运行NSTimer的OS X代理应用程序无法运行

时间:2015-08-30 10:32:40

标签: cocoa nstimer swift2 xcode7

我有一个OS X代理应用程序(只能从菜单栏中的图标运行)。我的应用程序会创建一个随机间隔的NSTimer来播放声音。

func setNewTimer(timeInterval: NSTimeInterval) {
    self.timer = NSTimer.scheduledTimerWithTimeInterval(timeInterval, target: self, selector: "playSound", userInfo: nil, repeats: false)
NSRunLoop.currentRunLoop().addTimer(self.timer!, forMode: NSRunLoopCommonModes)
    NSLog("Timer created for interval: \(timeInterval)")
}

应用程序在我启动它之后工作正常,并继续在其他应用程序中执行其他工作。它按预期随机播放声音。

如果计算机短时间内进入睡眠状态并返回,应用程序将按预期随机播放声音。

但是,如果我的电脑长时间睡眠(例如整个晚上),该应用程序将不再播放声音。

问题可能是计算机进入深度睡眠时可能会禁用计时器?或者(最好)是否有办法检测计算机是否从睡眠状态中醒来,以便我可以重置计时器?

注意:每次调用此函数时,我首先使用self.timer.invalidate()并重新计算timeInterval。在睡眠时间(例如23:00到08:00),计时器将不会运行,而是会创建一个从23:00到08:00的间隔,以便它可以“触发”。第二天早上。

1 个答案:

答案 0 :(得分:2)

我发现一段时间没有回复后,我自己想出了一个解决方案。解决方案非常简单,因为我只需要注册睡眠和唤醒通知(我添加了更新到Swift 3的代码):

// App should get notifified when it goes to sleep
func receiveSleepNotification(_ notification: Notification) {
    NSLog("Sleep nottification received: \(notification.name)")
    // do invalidation work
}

/// App should get notified when the PC wakes up from sleep
func receiveWakeNotification(_ notification: Notification) {
    NSLog("Wake nottification received: \(notification.name)")
    // Reset/Restart tasks
}

func registerForNotitications() {
    //These notifications are filed on NSWorkspace's notification center, not the default
    // notification center. You will not receive sleep/wake notifications if you file
    //with the default notification center.
    NSWorkspace.shared().notificationCenter.addObserver(self, selector: #selector(AppDelegate.receiveSleepNotification(_:)), name: NSNotification.Name.NSWorkspaceWillSleep, object: nil)
    NSWorkspace.shared().notificationCenter.addObserver(self, selector: #selector(AppDelegate.receiveWakeNotification(_:)), name: NSNotification.Name.NSWorkspaceDidWake, object: nil)
}

func deRegisterFromNotifications() {
    NSWorkspace.shared().notificationCenter.removeObserver(self)
}