Wednesday
Feb222012

Use KeepAlive and launchd to keep apps alive

Gabe over at Macdrifter wrote about his system for keeping up on what he needs to know. Two parts which caught my attention:

I keep Mail.app running to execute mail rules and perform spam and message filtering. For this purpose, I have a Keyboard Maestro scheduled task that restarts Mail if it is not running. The same goes for OmniFocus which is integral to some Mail rules. If there’s a problem running the task, I will get a notification via Prowl.

and

If Keyboard Maestro goes down several jobs will stop functioning. I will not receive alerts when this happens. Fortunately, this is a minor annoyance.

If you have tasks which have to be kept running, the easiest way to ensure that is by using launchd which has an option specifically to ensure that this happens. All you need is a properly formatted plist file in $HOME/Library/LaunchAgents which looks something like this:

<?xml version="1.0" encoding="UTF-8"?>
<!DOCTYPE plist PUBLIC "-//Apple//DTD PLIST 1.0//EN" "http://www.apple.com/DTDs/PropertyList-1.0.dtd">
<plist version="1.0">
<dict>
        <key>KeepAlive</key>
        <true/>
        <key>Label</key>
        <string>luoma.alwayson.dropbox</string>
        <key>ProgramArguments</key>
        <array>
                <string>/Applications/Dropbox.app/Contents/MacOS/Dropbox</string>
        </array>
</dict>
</plist>

Change “luoma.alwayson.dropbox” to whatever you want the process to the called, and change “/Applications/Dropbox.app/Contents/MacOS/Dropbox” to the path to the process you want to keep running. Note that you want the path to the executable itself, not just the .app wrapper. Also, for something like Keyboard Maestro you want the path to the ‘helper’ process, which is:

/Applications/Keyboard Maestro.app/Contents/Resources/Keyboard Maestro Engine.app/Contents/MacOS/Keyboard Maestro Engine

Note: Despite the spaces in that path, you do not need to quote it or escape them — launchd can handle it just fine.

Save the plist to your LaunchAgents folder with a name such as “luoma.alwayson.dropbox.plist” and then load it using launchctl:

launchctl load luoma.alwayson.dropbox.plist

The only ‘gotcha’ here is when you are ready to update whatever app you have set to KeepAlive. Your best option is to unload it first:

launchctl unload luoma.alwayson.dropbox.plist

to make sure that the automatic restart doesn’t interfere with the update process.

Also, make sure that the app is not set to automatically load at login, or you can end up with two copies running.

Repeat as necessary for any other apps that you want to keep running as long as you are logged in.

« Keep a log of Homebrew installations | Enable Web Sharing on OS X without using Sharing Preference Pane »

References (1)

References allow you to track sources for this article, as well as articles that were written in response to this article.