Launchd is the new cron, says Apple (iCal ain't so great at scheduled tasks)

One of our Apple servers is running an app that goes haywire if you don't reboot it periodically. So, I wrote an AppleScript to reboot the server, and created a recurring task in iCal to run the AppleScript every night. This worked fine for a few months but suddenly stopped working. A quick glance at the logs told me that the AppleScript I had created hadn't been run. When I opened iCal to see if something had happened to the recurring task, POOF! My script was run, and the server was restarted (during the day, which is what I was trying to avoid with the script to begin with!). After that the nightly iCal task ran fine.

Over the course of a year I figured out that the iCal glitch happens every few months; iCal forgets that it has scheduled tasks and doesn't run them. Why does this happen? I have no idea.

I've finally gotten around to fixing it and figured I should create a cron job, but Apple says "cron is so 1980's. You should use launchd!"

Creating a launchd job is not as easy as cron, but the concepts are pretty simple. Basically, this is how you do it:

  1. Create a plist, according to the specs, that describes your job. I found that using Apple's Property List Editor, included with the Apple Dev Tools, made the task much simpler and helped me avoid some syntax mistakes that I was sure to make otherwise.
  2. Place the plist in the appropriate folder. In my case I put it in /Library/LaunchAgents (check the spec to determine the appropriate location according to the task you're trying to perform)
  3. Load your job like this: launchctl load /path/to/your.plist

That was it. In the end I was able to get it to work by launching a bash script from launchd. In turn, the bash script launched my original AppleScript. It's kinda crazy and convoluted but it worked. AFP458.com has a great tutorial on launchd that helped me more than the apple document.

Leave a Reply

Your email address will not be published.