I would like to solve the issue from this question, namely, after disconnecting a Cinema display from a clamshell MacBook I would like to let the MacBook go to sleep without opening and closing the lid.
I have never used AppleScript before. Is it possible to write an AppleScript which puts the computer to sleep, say 30 seconds after disconnect of an external display, but only if the lid is closed.
Best Answer
Using the included Script Editor.app with OS X, try experimenting with these snippets.
Wait 30 Seconds
The following snippet will make your script wait 30 seconds before showing a dialog:
Sleep
The following snippet will put your Mac immediately to sleep:
Wait and then Sleep
Combining the two snippets above gives an AppleScript that will wait 30 seconds before putting your Mac to sleep:
Displays and Desktops
I am not sure how best to determine if a monitor is connected. You could certainly poll regularly; calling
system_profiler SPThunderboltDataType SPDisplaysDataType
and parsing the output would work.Polling is computationally expensive and best avoided.
Alternatively, maybe an approach whereby an AppleScript could determine if the number of active desktops has changed? When two monitors are connected to my Mac, the following snippet returns a two item list:
Expanding on this, the following snippet provides more display information to work with: