Use launchctl to fire an AppleScript script periodically

Posted by Daktari on Super User See other posts from Super User or by Daktari
Published on 2011-04-13T07:51:44Z Indexed on 2011/06/25 16:24 UTC
Read the original article Hit count: 409

I have written an AppleScript that lets me back up a particular file. The script runs fine inside AppleScript Editor: it does what it's supposed to do perfectly. So far so good.

Now I'd like to run this script at timed intervals. So I use launchctl & .plist to make this happen. That's where the trouble starts.

  • the script is loaded at set interval by launchctl
  • the AppleScript Editor (when open) brings its window (with that script) to the foreground but no code is executed
  • when AppleScript Editor is not running, nothing seems to be happening at all

Any ideas as to why this is not working?

--

After editing (as per Daniel Beck's suggestions) my plist now looks like:

<?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>KeepAlive</key>
<false/>
<key>Label</key>
<string>com.opera.autosave</string>
<key>ProgramArguments</key>
<array>
<string>osascript</string>
<string>/Users/user_name/Library/Scripts/opera_autosave_bak.scpt</string>
</array>
<key>StartInterval</key>
<integer>30</integer>
</dict>
</plist>

and the AppleScript I'm trying to run:

on appIsRunning(appName)
    tell application "System Events" to (name of processes) contains appName
end appIsRunning

--only run this script when Opera is running
if appIsRunning("Opera") then
    set base_path to "user_name:Library:Preferences:Opera Preferences:sessions:"
    set autosave_file to "test.txt"
    set autosave_file_old to "test_old.txt"
    set autosave_file_older to "test_older.txt"
    set autosave_file_oldest to "test_oldest.txt"
    set autosave_path to base_path & autosave_file
    set autosave_path_old to base_path & autosave_file_old
    set autosave_path_older to base_path & autosave_file_older
    set autosave_path_oldest to base_path & autosave_file_oldest
    set copied_file to "test copy.txt"
    set copied_path to base_path & copied_file

    tell application "Finder"
        duplicate file autosave_path
        delete file autosave_path_oldest
        set name of file autosave_path_older to autosave_file_oldest
        set name of file autosave_path_old to autosave_file_older
        set name of file copied_path to autosave_file_old
    end tell

end if

© Super User or respective owner

Related posts about osx

Related posts about osx-snow-leopard