Saturday, March 31, 2012

Basics of launchctl on Lion

I made a start on learning how to use launchd to run scripts. (An old) MacResearch tutorial is here. There is also a wikipedia page.

The basic usage is quite simple. We just need two files.
#! /usr/bin/python
from time import gmtime, strftime

fn = '/Users/telliott_admin/Desktop/time.txt'
FH = open(fn,'w')
FH.write(strftime("%a, %d %b %Y %H:%M:%S +0000", gmtime()))

Make sure the script is executable (I did chmod 755), and copy it to ~/Library/Scripts.

The other file is a plist that shows the details for what we want launchd to do:

<?xml version="1.0" encoding="UTF-8"?>
<!DOCTYPE plist PUBLIC "-//Apple Computer//DTD PLIST 1.0//EN" \
<plist version="1.0">

The plist goes in ~/Library/LaunchAgents.

There are many additional things you could do---the man page is here.

The script just writes the current time to a file on my Desktop. It is set to RunAtLoad (normally that would be login, but see below), and whenever the WatchPath changes. Here that is just a file which is also on my Desktop, but it could be a directory.

We can see if it's been loaded by doing:

> launchctl list | grep "com.TE"

Not yet.

We can manually (un)load it by doing:

launchctl load ~/Library/LaunchAgents/com.TE.script.plist
> launchctl list | grep "com.TE"
- 0 com.TE.script

When we do that we should see the file time.txt appear on the Desktop because we set RunAtLoad to true. Also, if the file y.txt is altered, say by:

> touch ~/Desktop/y.txt

The script should execute again.

No comments: