OS X: Triggering Automation Scripts Using launchd

Desktop management software, such as Casper, has the feature of running scripts when a computer meets a certain criteria. You can create a similar effect using launchd by creating a Launch Daemon or Launch Agent. These run in the background and you can use them to trigger a script to run. Basically, if you know how to script something, you can get it to run automatically via launchd
.
For example, you could create a daemon or agent that will:
- check the current wallpaper and change it if is not the correct value
- check the main volume name and change it back to “Macintosh HD” if it is named something else
- check the current network and change it to a different one (or remove a network from the preferred list)
Create The Launch Agent Or Daemon
You will need to create an XML file (saved as a .plist) that says to run your script. Below is a very simple one that run my script every 30 seconds. You can create it manually, or use an app like Lingon X.
<?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.jacobsalmela.myScript</string>
<key>ProgramArguments</key>
<array>
<string>/usr/local/triggers/myScript.py</string>
</array>
<key>RunAtLoad</key>
<false/>
<key>StartInterval</key>
<integer>30</integer>
</dict>
</plist>
The highlighted lines are the ones you would want to change. I usually store my scripts in /usr/local/triggers
, but you can put them wherever you want. You can also set the StartInterval to be whatever you want.
It is important that the .plist has the correct permissions and is in the correct location for how you want it to run. LaunchDaemons run at startup and typically run as root, LaunchAgents run at user login.
Set the permissions to mode 644
using this command:
chmod 644 /Library/LaunchDaemon/some.plist
Make sure the owner is root
and the group is wheel
:
chown root:wheel /Library/LaunchDaemon/some.plist
Now, install a script into the /usr/local/triggers
.
That’s it, once you reboot, the script should execute when your criteria is met.