Search code examples
macosapplescriptosascriptlaunch-agent

LaunchAgent plist doesn't find path to AppleScript in iCloud


For some reason, Dropbox terminates (crashes or quits) after being online a few days, with no explanation.

I therefore started to research a way for AppleScript to automatically restart the application when it terminates.

That led me to this script:

repeat
    delay 120 #Run every two minutes
    tell application "System Events"
        if name of every process does not contain "Dropbox" then tell application "Dropbox" to launch
    end tell
    delay 5
end repeat

I also want the script to run in the background, so I implemented my own variant of this Ask Different solution for launchctl.

In ~/Library/LaunchAgents/, I create a file named dropbox-keep-alive.plist with this content:

<?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>Label</key>
    <string>dropbox-keep-alive.job</string>
    <key>ProgramArguments</key>
    <array>
        <string>/usr/bin/osascript</string>
        <string>/Users/xxx/Library/Mobile\ Documents/com\~apple\~ScriptEditor2/Documents/dropbox-keep-alive.scpt</string>
    </array>
    <key>RunAtLoad</key>
    <true/>
</dict>
</plist>

The path to the AppleScript is given in the <array> above, and a .job label for launchutil is assigned under <key>.

I then load the .plist:

launchctl load -w ~/Library/LaunchAgents/dropbox-keep-alive.plist

And then start it:

launchctl start dropbox-keep-alive.job

For testing, I quit Dropbox and then wait 2+ minutes, but nothing happens.

If I try launchctl load -w again, I get the message that it's already loaded. launchctl start gives no response message.

I know that the AppleScript works because it's functional when running it with osascript directly. But somewhere in the .plist – or my management of launchctl – there is something that doesn't work.

I have tried to launchctl unload -w the script and redo the process. Any ideas?


Solution

  • launchd doesn't do shell-style parsing on strings, so the escapes you have in the path to the script will be interpreted as part of the actual filename... and it will not be found. It should look more like this:

    <key>ProgramArguments</key>
    <array>
        <string>/usr/bin/osascript</string>
        <string>/Users/xxx/Library/Mobile Documents/com~apple~ScriptEditor2/Documents/dropbox-keep-alive.scpt</string>
    </array>
    

    I'm not sure this is the only problem, but it certainly is a problem. If further debugging is needed, try capturing the error output from osascript by adding something like:

    <key>StandardErrorPath</key>
    <string>/Users/xxx/Library/Logs/dropbox-keep-alive.err</string>