Schedule job with crontab on macOS
Sometimes we have to do a specific job more often or repeatedly. Most of the time, we use the script to do the job for us.
Every time we have to run the script to do the job. It will be useful to schedule the script to execute at a specific time or on a particular pattern. That’s where the cronjob comes into handy.
The following are the steps to setup cronjob in macOS.
- Create a shell script and stored in the same location.
- Create a cron job in the Mac using the terminal. crontab is the command set up and maintain the crontab files for individual users.
man crontab
Check crontab -l to display the current crontab on standard output.
3. To edit the cron tab use the command
crontab -e
It will open the current crontab using the editor. We can add the job to the editor.
4. Configure the job by adding the out script along with cron schedule expressions.
0 4 * * 1–5 ~/Desktop/test.sh >> ~/Desktop/cron.log 2>&1
0 4 * * 1–5 - Set the execution of script At 04:00 on every day-of-week from Monday through Friday. For cron schedule refer here.
~/Desktop/test.sh - Path of the script has to execute.
~/Desktop/cron.log 2>&1- output the log to a file to ensure the script is executing.
5.Once the editor is saved and comes out(using:wq). The crontab will install automatically.
6. Make sure that the terminal app and cron executable as Full Disk Access. Can give full access in Settings -> Security & Privacy -> Privacy.
Can find the Cron executable in “/usr/sbin/cron”.
7. Check the cron.log file to see whether cron job is working as expected.