Running Recurring Background Tasks On Mac

Here’s a comprehensive guide on creating and deleting background tasks in macOS using LaunchAgents


Creating Background Tasks with LaunchAgents

  1. Create the .plist File
    Use a text editor to create a property list (.plist) file. For example, to create a task called caltoday: nano ~/Library/LaunchAgents/com.user.caltoday.plist
  2. Edit the .plist File
    Add the following content, replacing the <Command> and <Arguments> with your desired script or command:
<?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.user.caltoday</string>
    <key>ProgramArguments</key>
    <array>
        <string>/path/to/your/script</string>
    </array>
    <key>StartInterval</key>
    <integer>86400</integer> <!-- Run every 24 hours -->
</dict>
</plist>
  1. Save the file (Ctrl + O, then Enter, followed by Ctrl + X to exit).
  2. Load the Task
    Use launchctl to load the .plist file: launchctl load ~/Library/LaunchAgents/com.user.caltoday.plist
  3. Verify the Task is Loaded
    Check if the task is active: launchctl list | grep com.user.caltoday

Deleting Background Tasks with LaunchAgents

  1. Unload the .plist File
    Before deleting, unload the task to stop it from running: launchctl unload ~/Library/LaunchAgents/com.user.caltoday.plist
  2. Delete the .plist File
    Remove the .plist file to prevent it from being reloaded: rm ~/Library/LaunchAgents/com.user.caltoday.plist
  3. Verify the Task is Stopped
    Ensure the task is no longer active: launchctl list | grep com.user.caltoday

Example: Creating and Deleting a Task

Creating a caltoday Task

  • Write a script to print today’s date: echo "Today's date: $(date)" >> ~/Desktop/caltoday.log
  • Save it as ~/scripts/caltoday.sh and make it executable: chmod +x ~/scripts/caltoday.sh
  • Create a .plist file pointing to the script: <key>ProgramArguments</key> <array> <string>/Users/your-username/scripts/caltoday.sh</string> </array>

Deleting the Task

  • Unload the task: launchctl unload ~/Library/LaunchAgents/com.user.caltoday.plist
  • Delete the .plist: rm ~/Library/LaunchAgents/com.user.caltoday.plist