Remember to maintain security and privacy. Do not share sensitive information. Procedimento.com.br may make mistakes. Verify important information. Termo de Responsabilidade
In Unix-like operating systems, including macOS, the cron
utility is traditionally used for scheduling tasks. However, macOS has deprecated cron
in favor of launchd
, a more powerful and flexible service management framework. Understanding how to use launchd
is essential for automating tasks and managing system services on macOS. This article will guide you through creating and managing scheduled tasks using launchd
on macOS.
Examples:
Creating a Simple Scheduled Task with launchd:
To create a scheduled task that runs a script every day at a specific time, follow these steps:
a. Write the Script:
First, create a simple shell script. For example, create a script that writes the current date and time to a log file:
#!/bin/bash
echo "Current Date and Time: $(date)" >> /Users/yourusername/Desktop/log.txt
Save this script as log_time.sh
and make it executable:
chmod +x /Users/yourusername/Desktop/log_time.sh
b. Create a launchd Property List (plist) File:
Next, create a plist file that launchd
will use to schedule the task. Save the following XML content as com.yourusername.logtime.plist
in ~/Library/LaunchAgents/
:
<?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.yourusername.logtime</string>
<key>ProgramArguments</key>
<array>
<string>/Users/yourusername/Desktop/log_time.sh</string>
</array>
<key>StartCalendarInterval</key>
<dict>
<key>Hour</key>
<integer>14</integer>
<key>Minute</key>
<integer>0</integer>
</dict>
<key>StandardOutPath</key>
<string>/Users/yourusername/Desktop/log_time_output.log</string>
<key>StandardErrorPath</key>
<string>/Users/yourusername/Desktop/log_time_error.log</string>
</dict>
</plist>
This plist file schedules the script to run every day at 2:00 PM.
c. Load the plist File:
To load the plist file and start the scheduled task, use the following command:
launchctl load ~/Library/LaunchAgents/com.yourusername.logtime.plist
To verify that the task is loaded and running, you can use:
launchctl list | grep com.yourusername.logtime
Managing Scheduled Tasks:
If you need to stop and unload the scheduled task, use:
launchctl unload ~/Library/LaunchAgents/com.yourusername.logtime.plist
If you need to modify the task, edit the plist file and then unload and reload it:
launchctl unload ~/Library/LaunchAgents/com.yourusername.logtime.plist
launchctl load ~/Library/LaunchAgents/com.yourusername.logtime.plist