Getting Launchd to repeatedly run a script without waiting for previous launch to finish in OSX

270 views Asked by At

Let's say I have the script below

#! /bin/bash
sleep 300
dt=$(date '+%Y/%m/%d %H:%M:%S')
echo $dt >> /foo/bar/test.txt

When I set up a launchagent to trigger this script every 2 minutes... launchd will wait for the script to finish before triggering it again. So instead of the date every 2 minutes (after a 300 second sleep) I get it every 5 minutes or more. Is there a way for launchd to launch the script every 2 minutes, regardless of whether it has completed or not?

2

There are 2 answers

1
Gordon Davisson On BEST ANSWER

I haven't tested this, but you should be able to have the launch agent run the script in the background, something like this:

<key>ProgramArguments</key>
<array>
      <string>/bin/bash</string>
      <string>-c</string>
      <string>/path/to/script &</string>

</array>
<key>AbandonProcessGroup</key>
<true/>

Notes: If you need to pass any arguments to your script, include them in the same <string> as the script path, delimited by spaces (rather than as separate <string>s, like you normally would in the launch daemon file). The AbandonProcessGroup key is needed to prevent launchd from "helpfully" killing any leftover subprocesses (like your actual script) when what it thinks of as the daemon process exits.

0
Andrew Zimmer On

Gordon's answer is almost perfect--props to him.

The reason arlovande ran into issues was that the " &" part wasn't properly LaunchDaemon-ified. Anytime a space would happen, a new entry is needed under <array>

Therefore:

<key>ProgramArguments</key>
<array>
    <string>/bin/bash</string>
    <string>-c</string>
    <string>/path/to/script</string>
    <string>&</string>
</array>
<key>AbandonProcessGroup</key>
<true/>