I’ve been playing a lot lately with AppleScript and the Mac Automater app, both of which can do some pretty cool stuff. This gave me an idea: wouldn’t it be great if I could close certain applications when my commuters go to sleep?
I have a handful of programs that I run on both my MacBook and Mac Pro desktop at work, using file syncing tools like Dropbox or BTSync to keep the data files up to date on both machines. This generally works great, except that I have to remember to close the programs when I switch machines, otherwise I sometimes end up with unexpected results like locked files or, in some cases, data loss. I’m not so good at this and Apple doesn’t appear to provide a way to do it for me.
It didn’t take long, however, to find a free third-party utility that does. Sleepwatcher is a small daemon process that monitors the sate of your system and kicks off a shell script when certain system events occur. It can monitor for events such as sleep and wake up, display sleep and dimming, and even system idle (a specified period with no keyboard or mouse activity) and power status (when a MacBook switches from AC to battery power and vice-versa). It can also prevent the machine from sleeping based on the result of a script or it can run a script when another process prevents the system from sleeping. Sleepwatcher can be run as a system process (always running in the background, even when no users are logged in), as a user process for individual logged-in users, or both.
Before we get too far along, it should be noted that this may not be the best approach for all applications. The method I’m about to describe works best with applications that save their data files automatically, and exit without user intervention. While the applications will be shut down in a clean manner, you may have unexpected results if the application prompts you to save or to confirm that you really want to quit.
It is also very important to note that you should be extremely careful when implementing these scripts. An improper configuration could render your machine unable to sleep, wakeup, or even boot, so be sure to carefully test your scripts before enabling them to run automatically.
Installing Sleepwatcher from the developer’s site is a bit tricky as it comes with no installer and assumes some knowledge of the Unix command line. A much easier way to install it is to use a package manager such as Homebrew (I believe MacPorts can also install Sleepwatcher, but I’ve only done it with Homebrew). If you aren’t familiar with Homebrew, it is definitely worth checking out.
Assuming that you have Homebrew installed and working correctly, installing Sleepwatcher is as easy as running the following command in a terminal window:
brew install sleepwatcher
Homebrew will download and install Sleepwatcher at /usr/local/sbin/sleepwatcher. Note the followup instructions that Homebrew provides after installation, as we’ll get to them in a moment. Once the installation is is done, I recommend reading the man page, as it is the best way to get to know everything Sleepwatcher can do:
Now it’s time to write a sleep script. As we’ll find out in a moment, Sleepwatcher looks for user scripts named
~/.wakeup and system scripts named
/etc/rc.wakeup. Since we want to close programs that are running under our own UID, let’s choose the local user option.
First, create a file named
.sleep in your home directory using your editor of choice (mine is vi for this kind of stuff):
Then add the following to the file (in this example, I’m going to close the program KeePassX, my password manager, using AppleScript):
osascript -e 'tell application "KeyPassX" to quit'
If you want to close additional applications, simply add another osascript command for each additional application.
Why use AppleScript instead of something more bash-like, such as kill? AppleScript works inside the application, telling it to do a clean exit, such as if I pressed Comand-Q to close it myself. This allows the program to make sure files are saved and everything is in order before the process ends. Kill simply aborts the running process, regardless of what’s happening, which could result in data loss and other instabilities, which we’re trying to prevent in the first place.
After the script is saved, you’ll need to give it execute premissions:
chmod 700 ~/.sleep
New we’re ready to test the script. Enter the following in a terminal window to start Sleepwatcher:
/usr/local/sbin/sleepwatcher --verbose --sleep ~/.sleep
You won’t see anything happen; in fact, it will look like the terminal is hanging. Make sure KeePassX (or whatever program you added to the
.sleep file) is running and then close the lid of your MacBook (or go to Apple Menu > Sleep if you aren’t on a MacBook). Wait until the computer’s power light starts to slowly blink on and off, and then wake it by opening the lid and/or pressing the power button. The computer should resume exactly as you left it except that your target application should no longer be running. If anything went wrong, check the terminal window where you ran Sleepwatcher, it should show any errors that occurred. Press Control-C to stop Sleepwatcher.
Now it is time to configure launchd to run Sleepwatcher at startup or login. To do this, we need to add a plist file to our user or system’s LaunchAgents directory. Sleepwatcher comes with sample plist files that handle the four use cases mentioned above: user sleep, user wakeup, system sleep, and system wakeup.
If you only need support for sleep and wakeup, you can simply symlink the sample files to the proper LauchAgents directories. For this activity we only need to set up the user LaunchAgent since we aren’t using any system scripts:
ln -sfv /usr/local/Cellar/sleepwatcher/2.2/de.bernhard-baehr.sleepwatcher-20compatibility-localuser.plist ~/Library/LaunchAgents/
Then we tell launchd to load the configuration:
launchctl load ~/Library/LuanchAgents/de.bernhard-baehr.sleepwatcher-20compatibility-localuser.plist
Although not required in this example, to install the system agent, do the following:
sudo ln -sfv /usr/local/Cellar/sleepwatcher/2.2/de.bernhard-baehr.sleepwatcher-20compatibility.plist /Library/LaunchAgents/
sudo launchctl /Library/LaunchAgents/de.bernhard-baehr.sleepwatcher-20compatibility.plist
Note that you’ll need to be an administrator of the machine to install the system agent.
That’s about all there is to it! Sleepwatcher is now running in the background waiting for your computer to go to sleep. When they system does, Sleepwatcher will kick off your
.sleep script and, when the system resumes, Sleepwatcher will run your
.wakeup script (if you create one). And, since you also added the plist file to your LaunchAgents directory, launchd will find it and start Sleepwatcher every time your machine starts up or whenever you log in.
If you want to script other events, such as system idle or power status, you’ll need to make a copy of the sample plist file(s) and edit them by hand. Understanding the plist file format should be fairly straightforward if you compare the sample with the options described on the man page. Xcode features a graphical plist editor, but plists are simple XML files, so you can edit them in any text editor if you prefer.
Do you have a creative use for Sleepwatcher? Let me know about it in the comments.