MacOS Trigger on Sleep/Wake Event

Initially some time in 2020 I was looking for a way to trigger some custom actions when I put my Macbook Pro to sleep. I found someone asked this same question in 2011 on Apple Stake Exchange

The best answer, which was the newest when I came across the article was this.

Sleepwatcher

Was interested in that question previously but didn’t find any step by step guide on how to achieve it. Solution is based on open-source tool called sleepwatcher and apple launchd Was inspired by this article

  1. Install sleepwatcher: brew install sleepwatcher
  2. First create: ~/.wakeup and ~/.sleep scripts and put some shell logic in them.
  3. Add necessary permissions: chmod 700 ~/.sleep && chmod 700 ~/.wakeup
  4. Test it locally: /usr/local/sbin/sleepwatcher --verbose --sleep ~/.sleep
    1. go to sleep with running terminal
  5. If it works then load the process as launchd agent for all users: Library/LaunchAgents
  6. Add symlink for the sleepwatcher launchd task (replacing {version} with the version you have installed): sudo ln -sfv /usr/local/Cellar/sleepwatcher/{version}/de.bernhard-baehr.sleepwatcher-20compatibility.plist /Library/LaunchAgents/
  7. Load launchd task: sudo launchctl load /Library/LaunchAgents/de.bernhard-baehr.sleepwatcher-20compatibility.plist

Thanks for the write up Dzmitry Hubin!

Austin
Austin

πŸ’πŸ½β€β™‚οΈ Husband to Jeana.
⚾️ Dodgers & Brewers.
πŸ’» PHP Engineer.
πŸŒπŸΌβ€β™‚οΈGolfer; ~14 HDC.
🌱 Hydroponic Gardner.
🍿 Plex nerd.
πŸš™ '15 WRX, '22 Model 3 LR, & '66 Corvette C2.

Follow me on Twitter @TheFrosty & Instagram @TheFrosty.

Articles: 292