Opening an OS X disk image with a launchd agent while the display is sleeping
I created a launchd
agent which opens a non-password-protected sparse disk image (and mounts its solitary volume) daily at 2:45AM in preparation for backup software to write to the volume. The launchd
agent's plist file is saved in ~/Library/LaunchAgents/
. Here are the plist file's parameters:
Label: my.DiskImageOpener
KeepAlive: NO
RunAtLoad: NO
StartCalendar:
Hour: 2
Minute: 45
ProgramArguments:
hdiutil
attach
/path/to/MyDiskImage.sparseimage
As long as the computer's display is awake, the agent works as advertised, opening the disk image and mounting its volume at the time specified in the launch agent. On the other hand, if the display is asleep at the time specified in the launch agent, the disk image fails to open until the display is awoken from sleep (even if that is several hours later), at which point the disk image immediately opens and mounts its volume. The same phenomenon happens if I replace the hdiutil attach /path/to/MyDiskImage.sparseimage
command with open /path/to/MyDiskImage.sparseimage
, or place the command in a separate executable shell script that the launch agent executes. Also, even though the display is asleep when the above-described problem occurs, the computer itself is awake. Also, I tested having the launch agent execute a dummy executable shell script (echo $(date)
) instead of hdiutil
, and it executes normally even when the display is asleep.
So it seems that the problem occurs specifically when trying to open a disk image from a launchd
launch agent while the computer's display is asleep. Why does the display's sleep vs awake status have any effect on opening a disk image? How can I circumvent this problem?
I am grateful for any help with this puzzling problem. (I am using a MacBook Pro laptop running OS X 10.8.2 Mountain Lion.)
Solution 1:
It is likely your MacBook is asleep when launchd
is scheduled to run your disk mount command. launchd
does not change its behaviour because of the state of the display.
Your launchd job will run so long as:
- the Mac is awake
- the launchd job is active
- you are logged in (the job ticket is in ~/Library/)
Use pmset's debug logs to find out if your Mac was awake or asleep. The following command will print a log of everything pmset
knows:
pmset -g everything
Be sure to check the system.log
for messages related to your failed launchd job. If a problem is encountered launchd
will log a message.
Applications > Utilities > Console.app > system.log
Mac OS X Energy Saver includes the ability to power on or wake your Mac at a predefined time. You might want to use this ability to wake your Mac a minute before your launchd
job is scheduled.
System Preferences.app > Energy Saver > Schedule…