Launchd

Let's you automatically launch applications on startup, on disk mount, at certain times, etc

plist files

Example of plist file that launches a script every time a drive is mounted (then you can use

File.exists?("/Volumes/Mydrive")

to check if a specific drive is mounted, and do some action based on it.

<?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>kindle-clippings</string>
        <key>ProgramArguments</key>
        <array>
                <string>/Volumes/Home/stian/src/folders2web/kindle-mount.sh</string>
        </array>
        <key>StartOnMount</key>
        <true/>
</dict>
</plist>

Note that the ProgramArguments string can only be one word, which is why I wrapped the ruby command (which needs a -KU to work) in a shell script.

Loading/unloading plist files

To load, use launchctl

launchctl load [-w] file.plist

(-w means that the plist will be enabled on every reboot, otherwise it will only be active until the next reboot)

To unload

launchctl unload file.plist

(note that you do not use the reference key in the plist to unload, you have to point to an actual file on the disk).

Logging/troubleshooting

If something is going wrong, you can change the log level of launchd, and monitor the system log.

set log level to debug

sudo launchctl log level debug

(possible modes are debug, info, notice, warning, error, critical, alert, emergency)

tail the system.log

tail -f /var/log/system.log

all the error messages from for example Ruby will be listed here, together with messages indicating a failure to load the script at all

when you are done, set the launcdctr log level back to error

sudo launchctl log level error

(from Obscured Clarity)