What's the best way to catch sleep and resume events for OSX?

I want to make a timer that counts whenever the system (Mac OS X Yosemite) is turned on. My idea is to use python and listen to sleep and resume signals and increment the counter whenever the system is powered on. However, I have not been able to find much information on how to do this.

  • Would it be possible to solve this problem with what I have detailed?
  • Is there a better way to solve this problem?

Thank!

+3


source to share


1 answer


Here's an example using PyObjC (which should be installed by default on Yosemite, or possibly after installing Xcode):

#!/usr/bin/env python

from AppKit import NSWorkspace, NSWorkspaceWillSleepNotification, \
                   NSWorkspaceDidWakeNotification, NSObject, \
                   NSApplication, NSLog

class App(NSObject):

    def applicationDidFinishLaunching_(self, notification):
        workspace          = NSWorkspace.sharedWorkspace()
        notificationCenter = workspace.notificationCenter()
        notificationCenter.addObserver_selector_name_object_(
            self,
            self.receiveSleepNotification_,
            NSWorkspaceWillSleepNotification,
            None
        )
        notificationCenter.addObserver_selector_name_object_(
            self,
            self.receiveWakeNotification_,
            NSWorkspaceDidWakeNotification,
            None
        )

    def receiveSleepNotification_(self, notification):
        NSLog("receiveSleepNotification: %@", notification)

    def receiveWakeNotification_(self, notification):
        NSLog("receiveWakeNotification: %@", notification)

if __name__ == '__main__':
    sharedapp = NSApplication.sharedApplication()
    app       = App.alloc().init()
    sharedapp.setDelegate_(app)
    sharedapp.run()

      



(Based on this document )

0


source







All Articles