How to I stop a launchd script from running on wake

Solution 1:

The problem lies with launchd and how it handles jobs that are missed during sleep:

From the launchd.plist man page (man launchd.plist)

Unlike cron which skips job invocations when the computer is asleep,
launchd will start the job the next time the computer wakes up.  If
multiple intervals transpire before the computer is woken, those
events will be coalesced into one event upon wake from sleep.

So, there are a few options to consider...

  • revert to cron. Though deprecated, cron won't run jobs that have been missed

  • check for time of day before playing the sound (this can be done with a "wrapper" script or within the script itself.

  • write a log entry (somewhere). On script launch, parse the log. If a sound was played within the last 30 mins, don't play again.

Solution 2:

I had a similar issue and addressed it by using a shell conditional evaluation:

  <key>ProgramArguments</key>
  <array>
    <string>zsh</string>
    <string>-c</string>
    <string>minute=$(date +"%M");   if [[ $minute = 00 || $minute = 30 ]]; then afplay -v 2 /System/Library/Sounds/Submarine.aiff; fi</string>
  </array>