How to close applications on sleep?

I have a password management application (KeePassX) of which backup I sync over Dropbox across several computers.

However the password database can be open only on one computer at a time for file locking reasons. Problems arise when one computer goes to sleep and the application is left open on this computer, the database locks are never removed and in the worst case there are unsaved changes in the database.

Would it be possible to make a program to prompt closure on sleep (like with shutdown) or record a macro which closes the program when the computer puts itself to sleep or is made sleep through Apple menu?


Solution 1:

It's hard for me not to to question the validity of your setup (broken sync!), but ... for doing something on sleep or wake, you should try SleepWatcher by Bernhard Baehr (more context at Mac OS X Hints). It is using launchd for monitoring.

[SleepWatcher] is a command line tool (daemon) […] that monitors sleep, wakeup […] of a Mac. It can be used to execute a Unix command when the Mac […] goes to sleep mode or wakes up, […]

If you have a bit of terminal experience, I think you can set it up. Make sure you read the well-hidden "Installation for new SleepWatcher users" section in ReadMe.rtf

Solution 2:

Installing SleepWatcher:

wget http://www.bernhard-baehr.de/sleepwatcher_2.2.tgz
tar -xf sleepwatcher_2.2.tgz
sudo mkdir -p /usr/local/sbin /usr/local/share/man/man8
sudo cp sleepwatcher_2.2/sleepwatcher /usr/local/sbin
sudo cp sleepwatcher_2.2/sleepwatcher.8 /usr/local/share/man/man8
cp sleepwatcher_2.2/config/de.bernhard-baehr.sleepwatcher-20compatibility-localuser.plist ~/Library/LaunchAgents
launchctl load ~/Library/LaunchAgents/de.bernhard-baehr.sleepwatcher-20compatibility-localuser.plist
echo $'#!/bin/bash\ndate>/tmp/date'>~/.sleep
echo $'#!/bin/bash\nsay wake up'>~/.wakeup
chmod +x ~/.wakeup ~/.sleep

You can also test SleepWatcher by running /usr/local/sbin/sleepwatcher --verbose --sleep ~/.sleep --wakeup ~/.wakeup.

You can quit the application by running osascript -e 'quit app "Application Name"' or just killall Application\ Name.