launchd & me

This is a really technical, geek-y post and is probably of interest to very few of my readers, but over the weekend I finally figured out how to use Apple’s launchd to run my web stats program on a nightly basis.

Up to this point I’ve been ssh-ing into my server and running it manually. Kind of a pain. I’m more like a power user than a full-fledged server admin, though, and I hadn’t sat down and taken the time to figure out what needs to go where to get the process to run automagically on its own.

There are plenty of tutorials out there for using cron to run something. But I knew a couple of things:

  1. I was going to be using Mac OS X to run my server,
  2. Apple had come up with a nifty, Mac OS X-based tool called launchd,
  3. launchd was the primary method for scheduling, starting, and maintaining ongoing processes in Mac OS X Leopard (10.5)

…so it was a good thing to learn how to use the tool I was given, rather than rely on older tools.

Here’s a quick summary of the steps to take:

  1. Set up the script or program you want to run – I wrote a simple shell script to run webalizer.
  2. Write a text file in XML format that:
    • names the process;
    • gives the command for running the script (with the full path to the script);
    • names the time and frequency of when it should run.
  3. Save the XML file as a .plist into the proper directory – I put mine in /Library/LaunchDaemons/;
  4. use launchctl to load the plist as a process.

If you’re scared or unfamiliar with the command line, there are some GUI tools that help with this. The biggest help to me in getting started is a free program called Lingon. Lingon may be all that most users need; I needed to use the command line on my webserver, but I’m now also using Lingon on my laptop and home Mac.

Hmmm… I really meant this originally as a “yay, me!” post but I can see me turning this into a “How-to” post for anyone out there who might want to learn this, too. I’ll do that later, maybe. This is not a How-to.

For now, I’ve got the key to running programs on a regular basis on any Mac running 10.4 or newer… like finally automating that backup process I use from time to time. Or emailing my servers’ logs to me. Or… well, the sky’s the limit. launchd not only is able to run something on a periodic basis, it can watch a directory/folder and take action when the directory changes, or watch a continuously-running process and keep it up and running if it stops or crashes (lots of people use it to keep Quicksilver running).