Watch folder that only processes one item at a time

applescriptfinderfolder-action

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 {}
repeat
    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?

(To clarify: If you attach a folder action script to a folder, that script is launched multiple times, once for each time you add items to the folder, regardless of whether another instance of said script is already running. This is what I'm trying to avoid. For example, if 10 items are dropped into the watch folder, and then, while the first 10 items are still being processed, another 5 items are dropped, this will launch a second instance of the script.)

The only other thing I can come up with is to maintain a "status" file which will be set to "busy" by the script, and "idle" when done processing, so that the other instances of the script will wait for the "idle" state … but this is also awkward.

Best Answer

Try Hazel from https://www.noodlesoft.com

I haven’t had any processes that run that long, but in my experience Hazel always seems to operate sequentially on files, and won’t start a new process until the old one is done.

It’s an invaluable Mac app, IMO. I use it exclusively instead of Folder Actions. It’s a paid app, but there is a free, full-featured demo available. The developer is also very helpful and the app is well-maintained. Highly recommended.

I think your only other alternative is a lock file, which is awkward, as you mentioned.