Prevent a launchd job from rerunning until existing job finishes

I often need to schedule scripts to run at an interval, but I don’t know how long that script will take to complete and I don’t want the script to run again at its normal interval unless the script isn’t running.

I’ve done this with pid files and grepping through ps lists to exit the script if another instance is running, but I was wondering if there is something built into launchd to handle this.

It turns out that launchd does this by default. Just set up your job as normal using StartInterval and if your job hasn’t finished running by the next time it is scheduled to run, launchd will wait until the job finishes. If more than one schedule has passed, the missed jobs will be coalesced into one instance and run just once until the next scheduled run, much like it behaves if the machine goes to sleep.

Another win for launchd.