MacOS – Lauchd – Run task multiple times between time interval

cronlaunchdmacosschedule

I want to run a script every 15 minutes between 12:00 AM and 4:00 AM. Is there a way to do that with launchd?

I know you can specify and array of dictionaries using StartCalendarInterval to accomplish this, but I would like to easily be able to change the interval if I so desire. I was thinking something along the lines of combining StartCalendarInterval with StartInterval, but I don't know how I would specify a stopping time.

The other alternative is to check the time in my script I'm running, but once again, I think I'd rather use launchd to accomplish the task in case I want to add more scripts.

I'm pretty sure this can be done with cron as well (We could put it here for reference if anyone knows how), but I want to stick with launchd since Apple seems to be phasing out cron.

Best Answer

You can print the StartCalendarInterval dictionaries with something like this: for h in {0..4}; do for m in {0,15,30,45}; do echo "<dict><key>Hour</key><integer>$h</integer><key>Minute</key><integer>$m</integer><key>Second</key><integer>0</integer></dict>"; done; done.

You could also run the script every 15 minutes but exit it depending on the time:

h=$(date +%-H)
m=$(date +%-M)
[[ $h -gt 4 || $h -eq 4 && $m -ne 0 ]] && exit

Or run EDITOR=nano crontab -e and add a line like */15 0-4 * * * ~/bin/script.