【问题标题】:Detect when osx sleeps / resumes from sleep检测osx何时睡眠/从睡眠中恢复
【发布时间】:2012-12-06 20:36:18
【问题描述】:

是否可以编写一个 python 程序(我认为我将作为守护进程运行)来检测 osx 何时进入睡眠状态以及何时从睡眠中恢复?

如果听起来我没有对此进行研究,我深表歉意 - 我已经脱离了自己的舒适区,并且不确定是否需要将 python 委托给可以报告此问题的 C 语言编写的东西,或者那是不必要的。

【问题讨论】:

    标签: python c macos


    【解决方案1】:

    在 IOKit 中有执行此操作的工具 -- 具体来说,使用 IORegisterForSystemPower() 注册的回调将在系统休眠之前和唤醒之后立即调用。

    您可能想查看bb's sleepwatcher daemon,它可以在各种事件发生时调用您指定的命令,包括系统睡眠/唤醒,以及各种其他事件(显示睡眠/唤醒、系统空闲、关机) ...)。

    【讨论】:

    • 干杯 - sleepwatcher 看起来是一个非常简单的解决方案 :)
    【解决方案2】:

    Cocoa 开发者可以收听NSWorkspaceDidWakeNotification

    - (void) receiveSleepNote: (NSNotification*) note
    {
        NSLog(@"receiveSleepNote: %@", [note name]);
    }
    
    - (void) receiveWakeNote: (NSNotification*) note
    {
        NSLog(@"receiveWakeNote: %@", [note name]);
    }
    
    - (void) fileNotifications
    {
        //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 sharedWorkspace] notificationCenter] addObserver: self
                selector: @selector(receiveSleepNote:)
                name: NSWorkspaceWillSleepNotification object: NULL];
    
        [[[NSWorkspace sharedWorkspace] notificationCenter] addObserver: self
                selector: @selector(receiveWakeNote:)
                name: NSWorkspaceDidWakeNotification object: NULL];
    }
    

    此示例代码摘自此处的 Apple 文档:Registering and unregistering for sleep and wake notifications

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2023-04-04
      • 2012-11-14
      • 2012-04-07
      • 1970-01-01
      • 1970-01-01
      • 2020-09-02
      • 1970-01-01
      • 2015-08-22
      相关资源
      最近更新 更多