Here’s a comprehensive guide on creating and deleting background tasks in macOS using LaunchAgents …
Creating Background Tasks with LaunchAgents
- Create the
.plistFile
Use a text editor to create a property list (.plist) file. For example, to create a task calledcaltoday:nano ~/Library/LaunchAgents/com.user.caltoday.plist - Edit the
.plistFile
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>
- Save the file (
Ctrl + O, thenEnter, followed byCtrl + Xto exit). - Load the Task
Uselaunchctlto load the.plistfile:launchctl load ~/Library/LaunchAgents/com.user.caltoday.plist - Verify the Task is Loaded
Check if the task is active:launchctl list | grep com.user.caltoday
Deleting Background Tasks with LaunchAgents
- Unload the
.plistFile
Before deleting, unload the task to stop it from running:launchctl unload ~/Library/LaunchAgents/com.user.caltoday.plist - Delete the
.plistFile
Remove the.plistfile to prevent it from being reloaded:rm ~/Library/LaunchAgents/com.user.caltoday.plist - 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.shand make it executable:chmod +x ~/scripts/caltoday.sh - Create a
.plistfile 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