Using launchctl on Mac OSX 10.10 to run a script periodically

Lately I’ve been playing around with mutt, a “small but powerful text-based email client for Unix operating systems” and offlineimap, a software that downloads your mailbox as a local Maildir.

After I finally got everything set up (easier said than done), I needed a way to make offlineimap synchronize my mailbox periodically. Apple recommends usinglaunchctlinstead of crontab. The following example shows how to runofflineimapin quiet mode every two minutes:

<?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>Label</key>
  <string>com.kimgrytoyr.offlineimap.plist</string>
  <key>ProgramArguments</key>
  <array>
    <string>/usr/local/bin/offlineimap</string>
    <string>-u</string>
    <string>quiet</string>
  </array>
  <key>StartInterval</key>
  <integer>120</integer>
</dict>
</plist>

This file is basically an XML file, but the extension you must use is .plist. You would typically call it something like com.yourname.scriptname.plist. Place it in the folder ~/Library/LaunchAgents/, and make sure you replace yourname and scriptname with something relevant.

When you’ve saved the file to the specified location, type the following to load it into launchctl:

launchctl load ~/Library/LaunchAgents/com.yourname.scriptname.plist

If you ever need to remove it from launchctl, you can type the following:

launchctl remove ~/Library/LaunchAgents/com.yourname.scriptname.plist