Automating Tasks in OSX

This is lifted from my old research blog, but I find myself looking it up so often that I'm reposting here to make it easier to find. Click the post title to view the full article::

Since 10.4 the new way to set startup tasks is through the use of launch agents or launch daemons (launchd). These can be easily controlled with the launchctl service, here's the manual page:
http://developer.apple.com/mac/library/documentation/Darwin/Reference/M…


So, say we want to add a regular backup of some folder to the backup drive. We'll need to write a script to handle the backup. The following script mounts the volume, does the copy and some housekeeping (X.X.X.X = IP of your backup array):


mkdir /Volumes/scratch
mount_afp afp://username:password@X.X.X.X/Scratch /Volumes/scratch/
cp -R -v ~/repositories /Volumes/scratch/SubversionBackup/repoBackUpNew/
# CLEAN UP
rm -R /Volumes/scratch/SubversionBackup/repoBackUp/
mv /Volumes/scratch/SubversionBackup/repoBackUpNew /Volumes/scratch/SubversionBackup/repoBackUp

Lets save this in a file called "backup"

Once we're sure the script is running successfully, the next step is to automate it. To do this we use the launchchctl service and pass it a file called a PList as a parameter. Lets call it backupRepositories.plist . The PList is basically just the settings for the execution of your backup script. It needs to live off the root, in the following location:

/Library/LaunchAgents/

You could restart the machine at this point to load the PList, but lets just load it manaully from the command line:

launchctl load /Library/LaunchAgents/backupRepositories.plist

The dictionary element "Minute" has a value of 1440, so this PList is executed every 1440 minutes.
Here's the code for the PList file:

<?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"&gt;
<plist version="1.0">
<dict>
<key>Label</key>
<string>backupRepositories</string>
<key>ProgramArguments</key>
<array>
<string>/Users/svnuser/repositories/tools/backup</string>
</array>
<key>LowPriorityIO</key>
<true/>
<key>StartCalendarInterval</key>
<dict>
<key>Minute</key>
<integer>1440</integer>
</dict>
</dict>
</plist>