# Using launchd agents to schedule scripts on macOS

source: https://ift.tt/hZg8kmo tags: #literature #software-engineering uid: 202212291518

Write a plist for your agent

Unlike crontab jobs, LaunchAgents are written in (quite verbose) plist XML. We define a Label according to the name of our agent and then go on describing how it should behave (which program to run, what arguments, when to run it, etc.).

Example:

<?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>de.davidhamann.my-program</string>
    <key>ProgramArguments</key>
    <array>
        <string>/usr/local/bin/python3</string> <-- note how to run Python
        <string>/Users/user/path/to/my-program.py</string>
    </array>
    <key>StartInterval</key>
    <integer>30</integer>
</dict>
</plist>

Load and start the agent 🚀

LaunchAgents can be loaded, started and unloaded with launchctl. To do so, we need to supply the ID of our target user and the plist file we just created. You can get your user-id via id -u or id -u <the-username>, respectively.

Assuming we are in ~/Library/LaunchAgents/ we can now load our agent by executing the following command:

launchctl bootstrap gui/<your-user-id> de.davidhamann.my-program.plist


Date
February 22, 2023