TL;DR:
My problem: I need to close a program before my mac goes to sleep, but sometimes I forget.
My solution: use SleepWatcher to run an AppleScript that tells the app to quit. It's pretty technical.
I use IRC for work. Some people leave it open all the time; I prefer to use it as "office hours", and only have it open when I'm working and more-or-less interruptible.
One super annoying thing is, sometimes I leave for the day, close my laptop lid, but forget to exit IRC. This spams every channel with a ton of connect/disconnect messages overnight and into the next morning. Suck.
It happened again this week, and I got annoyed, and decided to find a way to prevent it from happening again.
Here's how I did it (on OSX 10.9 Mavericks):
- Install SleepWatcher, I used homebrew:
homebrew install sleepwatcher
- Note that the SleepWatcher readme is actually not super useful, although the homebrew output suggests that you read it.
- Create a file named
homebrew.mxcl.sleepwatcher.plist
inside~/Library/LaunchAgents
. The contents of that file are below.
- I only need to run commands for my specific user (I'm the only user on this machine). If I needed to run commands system-wide, I would have needed to put the plist file inside
/Library/LaunchDaemons
.
- The AppleScript I needed was a one-liner. Following the suggestion in the sample file, I created a file at
~/.sleep
, made it executable, then included the applscript stuffs. I also created an empty~/.wakeup
file, in case I want to use it later. - Finally, to load the sleepwatcher script, I did
launchctl load ~/Library/LaunchAgents/homebrew.mxcl.sleepwatcher.plist
.
Here's my ~/Library/LaunchAgents/homebrew.mxcl.sleepwatcher.plist
:
<?xml version="1.0" encoding="UTF-8"?>
<!DOCTYPE plist PUBLIC "-//Apple Computer//DTD PLIST 1.0//EN" "http://www.apple.com/DTDs/PropertyList-1.0.dtd">
<plist version="1.0">
<dict>
<key>Label</key>
<string>de.bernhard-baehr.sleepwatcher</string>
<key>ProgramArguments</key>
<array>
<string>/usr/local/sbin/sleepwatcher</string>
<string>-V</string>
<string>-s ~/.sleep</string>
<string>-w ~/.wakeup</string>
</array>
<key>RunAtLoad</key>
<true/>
<key>KeepAlive</key>
<true/>
</dict>
</plist>
And here's my ~/.sleep
file. Note that you need to set the executable bit; I did chmod 755
.
#!/usr/bin/osascript
tell application "LimeChat" to quit
You can test AppleScripts on the command line by doing osascript -s "some command"
, in this case
localhost:~ $ osascript -s 'tell application "LimeChat" to quit'
I ran into a problem where AppleScript would send the quit command, then LimeChat would display an "are you sure?" input box. While it's possible to use AppleScript to click "ok" in the confirmation box, LimeChat exposes a preference to disable that, so that seemed simpler: inside LimeChat's Preferences > Interface tab, I unchecked the "Confirm to quit the application" checkbox.
That's it! No more join/part spam if I forget to close IRC at the end of the day ^_^