Watch folder that only processes one item at a time?

I need to set up a watch folder that runs a script on each item added.
But the script could take 10 mins or more to process a single item.

What I’ve done is put this code at the top of my script that keeps watching the folder and then acts when something is added:

set watchFolderAlias to (POSIX file watchFolder as alias)
set r to {}
	tell application "Finder" to set r to (sort (get files of watchFolderAlias whose kind is "alias") by creation date)
	if (count of r) ≠ 0 then
		do(first item of r as alias)
	end if
	delay 5
end repeat

    on do(x)
       (* do 10 minutes of stuff with x *)
    end do

… and then I just keep it running. But this is cumbersome and awkward.

But if I attach the do() stuff as a folder action … then it will launch a new instance as soon as an item is added … right?

Am I missing a more elegant solution?

Maybe. When using launchd and create an launchd.plist file to create an WatchPath, I think you’ll find exactly what your looking for. Launchd makes sure one instance of the script is running and no more.

Really? I’ve never heard of that technique. Can you point me to a link for more info? gives me a lot of not very helpful links.

I found this guide ( but I’m not clear on how to specify only one instance … is that the default behavior?

launchd is the “first” and most important process running in your system. It’s an combination of init, cron, watchdog and rc processes (pre-Mac OS X 10.4) and it manages all applications, processes, daemons, services and scripts of your system. You can open an interface using launchctl on the command line or download an application which provides an GUI to manage launchd.

launchd.plist is the configuration file in plist format. Because Apple likes to change their online documentation almost every 6 months to make it "better’, man pages are again offline. So to read more about launchd.plist there is an well documented site about launchd.plist or you have to go to the terminal and type ‘man launchd.plist’. If you want to read the documentation in Preview you can type ‘man -t launchd.plist | open -f -a Preview’

I’ll hope this will get you started.