检测OSX何时进入睡眠/从睡眠中恢复

5

有没有可能编写一个Python程序(我认为我会将其作为守护程序运行),可以检测到OSX何时进入睡眠状态以及何时从睡眠状态恢复?

如果听起来像我没有研究过这个问题,那我很抱歉 - 我已经超出了自己的舒适区,并且不确定是否需要从Python委派到使用C编写的某些内容来报告此问题,或者这是不必要的。

2个回答

5

在IOKit中有相应的工具可以实现此功能--特别是,通过使用IORegisterForSystemPower()注册回调函数,在系统睡眠之前和唤醒之后都会被调用。

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


干杯 - sleepwatcher看起来是一个非常简单的解决方案 :) - Matt Roberts

3

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];
}

这段示例代码摘自苹果的文档,链接在此:注册和注销睡眠和唤醒通知

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接