Monday, September 27, 2010

forking a thread in AppleScript...

I searched everywhere to learn how to fork a background thread or process using Applescript. The best I could find is to use "do shell script" to start an osascript background process to run the second script. This works pretty well so long as your script works properly under osascript.

In my particular case, I was using Applescriptobjc to write a GUI for my collection of applescripts that assist data entry in a proprietary database I use at work.  Then I wanted a background process to control the visibility of this application depending on whether or not that program is the active window. The script then moves the position of the window to the bottom of that application's window.

The first option was to just have a separate applescript that would run separately. But now that I can fork a thread from within the main program, there is no need to do this. Here's the code I used:

    on DockUtility()
        set pathname to "/Applications/lightspeedhelper/"
        set scriptname to pathname & "StickToLightSpeed.scpt"
        set logfile to pathname & "StickToLightSpeed.log"
        set bgPID to ""
       
        do shell script "osascript " & scriptname & " &> " & logfile & " & echo $!" -- redirect output and send as bg thread
        set bgPID to the result
    end DockUtility

the shell script evaluates to:

osascript scriptname.scpt &> logfile.log & echo $!

This will launch osascript from a unix shell, redirect standard output and standard err to the log file (that is what you have to do for it to launch in the background) and the ampersand at the end means set it to launch in the background. The echo $! is a shell command that returns the process ID (PID) of this process. It is useful sometimes to have the bgPID there so you can later kill the process or check if it is active.

1 comment: