How to create an AppleScript that will quit an application at a specific time and then put the computer to sleep

applescriptapplicationsscriptsleep-wake

I've been toying around with AppleScript and Automator to get this thing to work, but I just can't seem wrap my head around it. If anyone could show me an example or give me some tips on how I can set an application to close at a specific time and then put the computer to sleep or shutdown, it would be greatly appreciated.

Best Answer

I'm assuming that you'd like to initiate this procedure as opposed to having it run at a regularly scheduled time.

My approach would be to initiate this from the command line, but any commands can be run in a shell script component of an Automator script with some modification. The following approach combines a few components to get the job done:

  1. A tell command to quit the application
  2. A command-line call to put the computer to sleep
  3. A command-line call to schedule 1 and 2 for a specific time.

1. Telling the Application to quit

This can be as simple as:

osascript -e 'tell application "AppName" to quit'

2. Putting the computer to sleep

Have a look at pmset for more details, but issuing the following command will put your computer to sleep:

pmset sleepnow

3. Scheduling an operation to be run at a specific time

Have a look at the at command. This command gives you the ability to specify a time for a command to run. You'll need to enable this functionality as it is not by default. To enable the atrun daemon, run the following command [reference on SU]:

sudo launchctl load -w /System/Library/LaunchDaemons/com.apple.atrun.plist

Once you've enabled atrun, any command can be scheduled for a specific time by issuing

echo "<command>" | at HH:MM

which works because at takes it's input from stdin by default. A simpler approach is to run commands listed in a file. A file can be executed by using the -f flag, followed by the name of the script to be run like this:

at -f /path/to/file HH:MM

Putting it all together

What follows assumes that atrun is enabled. As a toy example, let's say that I want to quit Mail and put the computer to sleep at 11PM. I would create the a file containing the commands that I want run as follows:

osascript -e 'tell application "Mail" to quit'
pmset sleepnow

Save that file to quit-and-sleep and then run on the command line

at -f /path/to/quit-and-sleep 23:00

Caveats

I didn't do any checking to make sure that Mail actually closed. The script also assumes that nothing else is going to get in the way of putting the computer to sleep. I've kept it simple here as a starting point for what you want.