Use launchd to replace folder actions

Apr 23, '08 07:30:03AM

Contributed by: Zeitkind

Folder actions are quite slow, and on 10.5.x, I found them to be not really fun to play with. Another way to watch a folder is to create your own launchd script. Here's one as an example:

<?xml version="1.0" encoding="UTF-8"?>
<!DOCTYPE plist PUBLIC "-//Apple//DTD PLIST 1.0//EN" "http://www.apple.com/DTDs/PropertyList-1.0.dtd">
<plist version="1.0">
<dict>
    <key>Disabled</key>
    <false/>
    <key>Label</key>
    <string>com.domain.whatever</string>
    <key>ProgramArguments</key>
    <array>
        <string>/Library/Scripts/domain/whatever.sh</string>
    </array>
    <key>QueueDirectories</key>
    <array>
        <string>/Volumes/hd/any/path/to/a/folder</string>
    </array>
    <key>RunAtLoad</key>
    <true/>
    <key>onDemand</key>
    <true/>
</dict>
</plist>
In the above, whatever.sh calls an AppleScript that automatically does something with newly arrived files (OCR, picture conversion, etc.):
#!/bin/bash
osascript /Library/Scripts/domain/whatever.scpt
This works fine, but you may find entries like this in you logs, repeated every 10 seconds:
01.04.08 10:54:17 com.apple.launchd[146] (com.domain.whatever) Throttling respawn: Will start in 9 seconds
01.04.08 10:54:28 com.apple.launchd[146] (com.domain.whatever) Throttling respawn: Will start in 8 seconds
01.04.08 10:54:38 com.apple.launchd[146] (com.domain.whatever) Throttling respawn: Will start in 9 seconds
In my case, I took the new files to OCR, saved them as PDFs, and removed the files after processing. But still, launchd started and stopped every 10 seconds. But why? The answer is quite easy: the Finder placed an invisible .DS_Store in that folder. My AppleScript did not remove it, but launchd was aware of that "new" file, and restarted endlessly. Fix: remove the .DS_Store as last action of your AppleScript:
set DeleteMe to alias "hd:any:path:to:a:folder:.DS_Store"
set rmMe to POSIX path of DeleteMe
try
    do shell script "rm " & quoted form of (rmMe)
end try
With this fix, launchd will stop restarting. There might be other ways to get rid off these .DS_Store's, but this was the easiest fix for me.

Comments (13)


Mac OS X Hints
http://hints.macworld.com/article.php?story=20080423051638134