Automatically wake up Mac and run a cron job
You use cron or Automator if you run jobs on your Mac regularly.
However, neither of these methods will work when your Mac is asleep; you should have your Mac wake up and go to sleep automatically.
Environment
- Mac mini Apple M1
- macOS Sonoma 14.1.2
Check the current settings
In macOS, you can set a cron using crontab. The current cron jobs is displayed with the following command:
terminal
$ crontab -l
Add a new cron
Enter the edit mode with the following command:
terminal
$ crontab -e
For example, run the shell script periodically every 10 minutes.
crontab
*/10 * * * * sh path/to/tmp.sh
The logs are printed out to the file. Note that this way overwrites the log file.
crontab
*/10 * * * * sh path/to/tmp.sh > path/to/tmp.log 2>&1
Reference: crontab(5) - Linux manual page
Power setting
You can manage the power settings of your Mac with pmset
command. To run a cron while sleeping, you should set the wakeup schedule before running the cron.
For example, wake up the Mac every day at 6pm.
terminal
$ sudo pmset repeat wake MTWRFSU 18:00:00
*MTWRFSU: all days from Monday through Sunday
It doesn't seem to use a wild card to set the schedule. The way to check the current schedule is to use the following command:
terminal
$ pmset -g sched
*In the previous version of macOS, you could schedule power settings using the Preference app, but now the CLI can be only available.
Power settings with cron
You can set the schedule to turn your Mac on and off with repeat
, but you can run it only once a day. To set the more complex schedule, you should use a cron in parallel.
For example, wake up your Mac at 59 minutes 30 seconds every hour.
repeat.sh
#!/bin/bash
time="$(date +"%m/%d/%y %H:59:30")"
sudo pmset schedule wake "${time}"
To use pmset
, you must set it with root.
terminal
$ sudo su
$ crontab -e
crontab
0 * * * * sh path/to/repeat.sh
Reference: Schedule your Mac to turn on or off in Terminal - Apple Support