MacOS – How to make a LaunchAgent with StartCalendarInterval

cronlaunchdmacosscript

I want to start replacing crontabs with LaunchAgents. My first attempt is not working.

<?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.nocturnal.mcworldsBackup</string>
    <key>ProgramArguments</key>
    <array>
            <string>~/bin/mcworldsBackup.sh</string>
    </array>
    <key>StartCalendarInterval</key>
    <dict>
            <key>Hour</key>
            <integer>4</integer>
            <key>Minute</key>
            <integer>30</integer>
    </dict>
</dict>
</plist>

The script mcworldsBackup.sh works fine standalone. I've made it log a timestamp to a file each time it runs and so far launchd has not executed it a single time.

I've checked and repaired the permissions of my Disk using DiskUtility, the plist is in ~/Library/LaunchAgents/com.nocturnal.mcworldsBackup.plist with permissions 0644, same as all the other .plist files already in there. They're all owned by me:staff.

If I grep for mcworldsBackup.sh in /var/log/* I find nothing, no clues as to why it's not being executed.

After I first created the plist I have logged out and logged back in, also rebooted the computer several times even though the documentation says you only need to login.

Best Answer

You must specify the full path in ProgramArguments. Things which your shell normally expands, such as ~ and * are not expanded by launchd.

After making those changes, this LaunchAgent worked for me.

You said you made these changes, but it didn't fix it. It is possible that you did not reload the LaunchAgent after making the changes.

Troubleshooting LaunchAgents

You can check if your LaunchAgent is currently loaded by running

launchctl list | grep com.nocturnal.mcworldsBackup

If it is not running, you can load it by using

launchctl load ~/Library/LaunchAgents/com.nocturnal.mcworldsBackup.plist

If you make any changes to the plist file, you will need to unload it using

luanchctl unload ~/Library/LaunchAgents/com.nocturnal.mcworldsBackup.plist

You will then need to load it again, using the command from above.

If you want to force the LaunchAgent to start now, instead of waiting until 4:30, you can run

launchctl start com.nocturnal.mcworldsBackup

You can then list it using

launchctl list | grep com.nocturnal.mcworldsBackup

The first column of the result is the PID of the process, if it is currently running. The second column is the exit code returned last time it was run. Use this to check if it ran properly. If not, the error message is written to /var/log/system.log.