CRON is a time-based job scheduler in Unix-like operating systems. It allows users to schedule scripts or commands to run automatically at specified intervals.
A CRON job is defined using the following syntax:
* * * * * /path/to/command
- - - - -
| | | | |
| | | | +---- Day of the week (0 - 7, Sunday is both 0 and 7)
| | | +------ Month (1 - 12)
| | +-------- Day of the month (1 - 31)
| +---------- Hour (0 - 23)
+------------ Minute (0 - 59)
0 5 * * * /path/to/script.sh: Runs the script every day at 5:00 AM.*/15 * * * * /path/to/script.sh: Runs the script every 15 minutes.
To schedule job.sh using CRON:
- Open the CRON editor:
crontab -e
- Add the following line to schedule
job.sh(e.g., every day at 2:00 AM):0 2 * * * /path/to/job.sh >> /path/to/job.log 2>&1
0 2 * * *: Runs the script at 2:00 AM every day./path/to/job.sh: Full path to thejob.shscript.>> /path/to/job.log 2>&1: Appends output and errors tojob.log.
To view scheduled CRON jobs:
crontab -l-
Ensure
job.shis executable:chmod +x /path/to/job.sh
-
Use absolute paths in
job.shto avoid issues with relative paths. -
Ensure that
crontabhas access to the file. On macOS (e.g., macOS Sequoia),crontabdoes not have access to folders or files by default. You need to grant access explicitly in the System Settings:
- Go to System Settings > Privacy & Security > Full Disk Access.
- Add your terminal application (e.g., Terminal, iTerm) to the list.
- Restart the terminal and reconfigure your
crontabif necessary.