AppleScript Primer for Mac OS X
Subject:   CLI, Applescript, and cron
Date:   2002-06-03 20:25:08
From:   clf8
What you didn't touch on in the article is calling Applescripts from the terminal. /usr/bin/osascript, osacompile, and osalang.

I wrote a basic script that tells iTunes to play my WakeUp playlist in the morning, and saved it in the Library/Scripts in my home (~) directory. From the Terminal you can run "/usr/bin/osascript /Users/bob/Library/Scripts/iTunesWakeup.scpt", without the quotes. .scpt seems to be the recommended extension, and you can save it as plain text (edited in vi or your favorite editor), or in the Script Editor format.

From the command line, this works. But you've got to have some way to get it to run at the right time. One kludge (I use it as a sleep timer because of 'at' problems) is to write a script, I call it bed and put it in my ~/bin.

sleep 1800;/Users/flowers/bin/iTunesStop &

Not much to it. When bed runs, it sleeps for 1800 seconds (30 minutes), then tells iTunes to stop. The & at the end puts the process in the background and returns the command prompt. The & will not work without the #!/bin/tcsh at the top. This is a complete hack, but it works.

But OS X is unix, and it has cron. Why can't I schedule a cron job to call my Applescript? Well, for some reason you can and you can't. This has worked on and off since 10.0 through 10.1.4. Actually, it usually worked right after an update for a couple of days/weeks. Then, and I don't know why, it stops working. Since cron can send you the output from your jobs, i've got a log of what gets returned when this happens:
zsh: read-only variable: PWD
syntax error: Can't get the application's event dictionary. (-2709)

I don't get that error when I call it myself, but the exact line called from cron gives this error. Can you all from O'Reilly help out with this one, or is the Terminal/Applescript integration just not there yet?

As for a replacement for the "bed" script, 'at' is a program that allows convenient scheduling of scripts. To use it, it has to first be enabled in the /etc/crontab. To do this, su to root and remove the "#" from the start of the /usr/libexec/atrun line. After that "kill -HUP pid" where pid is cron's process id, this will restart cron and reread the crontab. As always, if you're done being root, stop being root.

'at' allows command scheduling like 'at +2 min', then users enter commands/scripts, terminated with Ctrl-D. Every 10 minutes, atrun executes and checks for any jobs that are expired. No, at isn't the most precise of timers, but it works well for this purpose. And, if you want to increase the resolution, you can go back and edit the crontab.

But, for some reason cron cannot call Applescripts properly. Does anyone have this working, or an explanation of what might be going wrong?