2 min | mac
Prevent sleep or screensaver on macOS via launchd
In this post we will use a launchd agent to prevent macOS from going to sleep or activating the screensaver. This is particularly useful if you have a Mac laptop, enrolled in an MDM, with a policy that enforces the screensaver after a few minutes of inactivity. As a bonus tip we can tweak the agent to prevent sleep on battery power, a setting that was removed in the most recent versions of macOS.
Let’s start with a quick and easy terminal version, using a built-in command in macOS, our initial aim is to keep our Mac up and running at all time with the display on and the screensaver disabled.
It’s as easy as opening-up a terminal window and executing the following command:
caffeinate -dimsu
Minimise the terminal and keep it running, your Mac will stay on indefinitely. You can find a detailed explaination of the arguments used in the caffeinate man page.
We can use the same command to only prevent our Mac from going to sleep, when on battery power, by running caffeinate without any arguments:
caffeinate
This last command will allow your Mac to enable the screensaver and switch-off the screen following your systems settings, it will also allow sleep if you close the lid.
Now that we have the basics covered we can automate the process using a launchd agent so that we don’t need to keep the terminal window open and it will automatically run if we reboot our mac.
To do so, let’s create a launchd script called nosleep.caffeinate.plist on the desktop using your favorite text editor:
<?xml version="1.0" encoding="UTF-8"?>
<!DOCTYPE plist PUBLIC "-//Apple//DTD PLIST 1.0//EN" "http://www.apple.com/DTDs/PropertyList-1.0.dtd">
<plist version="1.0">
<dict>
<key>Label</key>
<string>com.nosleep.caffeinate</string>
<key>ProgramArguments</key>
<array>
<string>/usr/bin/caffeinate</string>
</array>
<key>RunAtLoad</key>
<true/>
</dict>
</plist>
The script above will only prevent sleep on battery power, exactly the same as running the caffeinate command in terminal without any arguments.
If our aim is to also keep the mac alive at all times we will need to add the additional arguments by tweaking the array section like this:
...
<key>ProgramArguments</key>
<array>
<string>/usr/bin/caffeinate</string>
<string>-dimsu</string>
</array>
...
The last step is to install the script in the local user Launch Agents, it’s as easy as creating the folder and coping the script into it and we can do it via terminal:
mkdir -p $HOME/Library/LaunchAgents
cp nosleep.caffeinate.plist $HOME/Library/LaunchAgents
If everything is correctly installed, you will get a notification for the new launchd agent in Notification Centre.
That’s all folks 👋 your Mac can now enjoy the drawbacks of sleep deprivation 😀