Monthly Archives: December 2009

Using at for command scheduling under Mac OS X

Mac OS X contains the handy at command for scheduling commands to run at a later time.  at is used to schedule the commands, and the atrun utility is used to execute the jobs.  However, by default the atrun utility isn’t enabled, any jobs scheduled via at will never run, with no particular warning.  The reason given in the man page for atrun is to “prevent disk access every 10 minutes”, which would be detrimental to laptop battery life and the computer going to sleep.

To enable atrun, execute the following

sudo launchctl load -w /System/Library/LaunchDaemons/

Once this is done, you may now use the at command.  For example, to schedule a command to run at 11am today, simply type:

[Mac-Book-Pro]$ at 11:30 am today

Then enter the desired command(s) and use Ctrl-D (end of file) to end input

touch diditrun
pwd > output.txt
job 13 at Sun Dec 20 11:30:00 2009

The example commands above will simply create a 0 length file (diditrun) and output the working directory of the command execution, as simple proof that it indeed has run.  You can review the jobs queued using atq (or at -l)

[Mac-Book-Pro]$ atq
13    Sun Dec 20 11:30:00 2009

To review the actual commands to be executed for any particular job (where 13 is the job number listed via atq):

[Mac-Book-Pro]$ at -c 13
# atrun uid=501 gid=501
# mail tplatt 0
umask 22
(... much output removed ...)
PATH=/Users/tplatt/depot_tools:/usr/bin:/bin:/usr/sbin:/sbin:/usr/local/bin:/usr/X11/bin; export PATH
PWD=/Users/tplatt/compression\ testing; export PWD
(... more output removed ...)
cd /Users/tplatt/compression\ testing || {
 echo 'Execution directory inaccessible' >&2
 exit 1
OLDPWD=/Users/tplatt; export OLDPWD
touch diditrun
pwd > output.txt

Notice that the command will be executed in the working directory in which it was scheduled, and with the user credentials of the user who scheduled it.
To remove a job from queue use atrm and the relevant job number

atrm 13

To disable the atrun command from running, you can again manipulate launchd settings via launchctl.  You would do this if you were not actively using at and wanted to prevent extraneous disk access and to ensure the computer sleeps properly.

sudo launchctl unload -w /System/Library/LaunchDaemons/

Lastly, at is intended for running commands in the future, but only once, not on a recurring basis.  For commands you wish to run on a recurring basis, use crontab.