cocoa - 后台带有 NSTimer 的 OS X 代理应用程序在深度 sleep 后无法工作

标签 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)")
}

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

如果计算机短暂进入休眠状态并返回,应用程序将继续按预期随机播放声音。

但是,如果我的计算机长时间处于 sleep 状态(例如整个晚上),应用程序将不再播放声音。

问题可能是如果计算机进入深度 sleep ,计时器可能会被禁用?或者(最好)有没有办法检测计算机从 sleep 中唤醒,以便我可以重置计时器?

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

最佳答案

发现有一段时间没有回复后,我自己想出了一个解决方案。解决方案非常简单,因为我只需要注册 sleep 和唤醒通知(我添加了更新到 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)
}

关于cocoa - 后台带有 NSTimer 的 OS X 代理应用程序在深度 sleep 后无法工作,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/32295589/

相关文章:

xcode - 以编程方式构建 ViewController 的 View 时,使编译器了解 NSView 子类方法

ios - swift/Xcode6 : How to change when the UIButton functionality is called after clicking the button

iphone - scheduledTimerWithTimeInterval vs performselector with delay with iOS 5.0

ios - 按按钮减少的计时器

ios - 如何在 Swift 中添加带有 GIF 背景的 UIButtons?

json - 如何解决错误 : "Invalid type in JSON write (NSConcreteData)"

cocoa - 如何从 Cocoa 应用程序创建 "print utility"?

cocoa - 使用绑定(bind)填充 NSOutlineView - KVO 添加项目

objective-c - NSDictionary Objective-C

ios - 滑动删除时如何让tableViewCell不展开