Running script through launchd with no annoying prompts

applescriptlaunchdsnow leopard

I have an applescript that checks my macbook battery and forces hibernation when it reaches a certain level, after displaying a 60 sec countdown.

I've successfully set it up to run in the background via launchd, every 30 secs, as a script but this causes an annoying bouncing icon on the dock.

So, I saved the script as an app and now the dock icon is no longer bouncing but if I am in the terminal app (for example) and I happen to be pressing CONTROL just as it launches in the background, I get the dreaded "Press Run to run this script, or Quit to quit" dialog box. And yes I have made sure that when I save it the "Startup Screen" option is NOT selected.

dialog

This dialog appears behind all other windows so I have no idea that it has happened and my app/script is stuck at this point.

Any suggestions how to overcome this so I can run my script with no annoying dialogs or bouncing icons?

Thanks.

EDIT: One idea that came to mind was to use the ExitTimeOut option in the plist file. The man page says:

ExitTimeOut <integer>
    The amount of time launchd waits before sending a SIGKILL signal. The default value is 20 seconds. The
    value zero is interpreted as infinity.

So I added it in like this:

<key>ServiceDescription</key>
    <string>Battery Monitor</string>
<key>StartInterval</key>
    <integer>30</integer>
<key>ExitTimeOut</key>
    <integer>90</integer>

then did unload/load of the .plist file. Unfortunately it doesn't appear to work. Am I understanding this option wrong?

Best Answer

Convert to Shell Script and AppleScript Pair

Convert your check for the battery status to a shell script. The shell script can then run regularly through a launchd job ticket without presenting any user interface.

When the conditions are met, your shell script can launch an AppleScript to interact with the user.

This assumes you use an ~/Library/LaunchAgent approach for the launchd job ticket. A computer wide launchd job will not be able to launch the AppleScript component in the appropriate user session.

Alternatively, you could use a third party tool to trigger on a battery event, such as Power Manager; this would avoid polling your battery and improve your battery's performance.