999Running Repetitive Jobs on OSX

Traditionally Unix systems use crontab to schedule and run repetitive jobs, OSX uses launchd, an init and operating system service management daemon.

Here is a script that call my index.php every 120 seconds. (I am download snow webcams in the index.php.)

<?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>org.trembl.snow</string>
  <key>ServiceDescription</key>
  <string>Getting Snow Pictures</string>
  <key>ProgramArguments</key>
  <array>
    <string>/Applications/XAMPP/bin/php</string>
    <string>/Applications/XAMPP/xamppfiles/htdocs/snow/index.php</string>
  </array>
  <key>RunAtLoad</key>
  <true/>
  <key>StartInterval</key>
  <integer>120</integer>
</dict>
</plist>

In Xcode, the same script looks like this:

Troubleshooting

I made a couple of errors, trying to get the script to run.

  1. Permissions sudo chown <user>:staff org.trembl.snow.plist
    Incorrect permissions also cause the Load failed: 122: Path had bad ownership/permissions

  2. The name of the file and the Label need to match. org.trembl.snow and org.trembl.snow.plist

  3. The plist need to be placed into ~/Library/LaunchAgents.

  4. If your Program has arguments, they need to be specified in an array:

    <key>ProgramArguments</key>
    <array>
    <string>/Applications/XAMPP/bin/php</string>
    <string>/Applications/XAMPP/xamppfiles/htdocs/snow/index.php</string>
    </array>
  5. Both strings need to be absolute. I got this error: Load failed: 122: Path had bad ownership/permissions, which was caused by only saying index.php instead of the whole absolute path.

  6. Use launchctl bootstrap and not the obsolete launchctl load.

  7. Launch with sudo launchctl bootstrap gui/`id -u` ~/Library/LaunchAgents/org.trembl.snow.plist

  8. Stop: sudo launchctl bootout gui/`id -u` ~/Library/LaunchAgents/org.trembl.snow.plist