Sub topic 8
Stopping runs from overlapping
This chapter assumes you can write a short bash script, know that cron runs commands on a schedule, and have read the earlier chapters on timeouts and exit codes. Here you will make sure a new run never starts while the previous one is still working.
Why overlap happens
A scheduler starts jobs by the clock. It does not check whether the last job finished. Agent runs vary a lot in length, so overlap is more likely than it is with a typical script.
Common causes:
- The run is slower than usual because the task was larger or the model API was slow.
- The timeout is longer than the schedule interval. A 90-minute timeout on an hourly job guarantees overlap on a bad day.
- Someone starts a manual test while the scheduled run is active.
- A catch-up run fires after a reboot (
Persistent=truein systemd) just as the regular timer fires. - A previous run hung and the timeout did not take effect.
Two agents running at once cause problems that a single run does not:
- Both edit the same working tree, so one run's uncommitted changes appear in the other's
git diff. - Both try to create the same branch or pull request, and one fails or creates a duplicate.
- Both read the same task list and do the same work twice.
- Cost and API rate-limit use doubles.
The cheapest fix is a lock. The job takes the lock at the start, and a second run that cannot get it exits right away.
Locking with flock
flock is a Linux utility from util-linux. It takes an advisory lock on a file descriptor. "Advisory" means the lock only works if every process that matters also asks for it. The wrapper script from the earlier chapter uses this pattern:
exec 9>"$HOME/.nightly-agent.lock"
if ! flock -n 9; then
echo "previous run still active, skipping" >> "$LOG_DIR/skipped.log"
exit 0
fiEach line does a specific job:
exec 9>fileopens the lock file for writing on file descriptor 9 and keeps it open for the life of the script. The number 9 is arbitrary, but it must not collide with descriptors you already use.flock -n 9tries to lock that descriptor.-nmeans non-blocking: fail immediately instead of waiting.- The lock belongs to the open file, not to the file's existence. When the script exits, for any reason, the kernel closes descriptor 9 and releases the lock. That includes
kill -9and a crash.
The last point is the main reason to prefer flock over a PID file. A PID file left behind by a crashed run says "running" forever, and your job has to decide whether the PID is stale. A flock lock cannot go stale in that way.
Try it before you trust it
You can test locking without an agent. Save this as lock-demo.sh:
#!/usr/bin/env bash
# lock-demo.sh: shows a second copy being skipped while the first holds the lock.
exec 9>"/tmp/lock-demo.lock"
if ! flock -n 9; then
echo "$(date -u +%FT%TZ) skipped: lock held" >&2
exit 0
fi
echo "$(date -u +%FT%TZ) got lock, working"
sleep 30
echo "$(date -u +%FT%TZ) done"Then start two copies a second apart:
chmod +x lock-demo.sh
./lock-demo.sh & sleep 1; ./lock-demo.sh; waitThe first copy prints "got lock". The second prints "skipped" at once. After about 30 seconds the first prints "done". Run it again afterwards and it gets the lock, which shows that nothing stale was left behind.
Choosing what a skip means
A skipped run is not a failure of the job, but it is a signal. You have to decide how it appears to the scheduler and to you.
| Choice | Effect | Use when |
|---|---|---|
| `exit 0` and log the skip | The scheduler sees success. Nothing alerts. | An occasional skip is normal, for example when someone runs the job manually. |
| Exit non-zero on skip | The scheduler records a failure and may alert. | Overlap should never happen and you want to hear about it. |
| Wait with `flock -w 300 9` | The run queues for up to 300 seconds, then fails. | The work must happen eventually and a short delay is fine. |
The wrapper from the earlier chapter exits 0 and appends to skipped.log. That is reasonable, but add a check for repeated skips. If the last several runs were all skipped, the run holding the lock is probably hung, and nobody is told. The chapter on alerting covers watching for this kind of silence.
Locking in each scheduler
The wrapper-script lock works under any scheduler, because it lives in the script. Each scheduler also has built-in behavior worth knowing, so you can tell what is already protected.
cron
cron has no overlap protection. It starts the command every time the schedule matches. Lock inside the wrapper, or wrap the command directly in the crontab:
PATH=/usr/local/bin:/usr/bin:/bin
0 2 * * 1-5 flock -n /home/deploy/.nightly-agent.lock /home/deploy/bin/nightly-agent.shThis form is shorter, but a skipped run is silent, because flock -n exits with status 1 and cron mails nothing useful. Locking inside the script lets you log the skip.
systemd timers
A timer activates its service unit. If the service is still running (state activating for a Type=oneshot unit), a new trigger does not start a second copy. systemd handles overlap for you, as long as the one service unit is the only way the job starts. A manual ./nightly-agent.sh from a shell bypasses it, so keep the flock in the script as well.
CI schedules
In GitHub Actions the concurrency block in the earlier workflow does the locking:
concurrency:
group: nightly-agent
cancel-in-progress: falseWith cancel-in-progress: false, a new run waits for the running one to finish instead of cancelling it. Only one run can be pending per group. If a third run arrives while one is running and one is waiting, the older waiting run is cancelled and replaced. For a nightly job that is usually what you want. Setting it to true would cancel an agent mid-edit, which can leave a half-finished branch.
Gotchas
- Do not delete the lock file. The lock is on the open file. If you remove it while a run holds it, the next run creates a new file with a different identity and gets a lock too. Leave the file in place.
- Use one fixed path. Two scripts that use different lock paths do not exclude each other. Avoid
/tmpif a cleanup service empties it, and avoid paths that differ per user. - Lock on local disk.
flockon network filesystems such as NFS can behave unreliably, depending on mount options. - A lock is per machine. If two hosts run the same job, a local
flockdoes nothing across them. Use a CI concurrency group, a single designated host, or a shared marker such as an existing open pull request for the branch (see the chapter on idempotency). - Children inherit the descriptor. If the agent starts a background process that outlives it, that process keeps descriptor 9 open and the lock stays held. This is often the right behavior, since work is still running. If it is not what you want, start the child with
9>&-to close the descriptor for it. - macOS has no
flockcommand by default. Install it (brew install flock) or use an atomicmkdirlock with a trap to remove the directory. That approach can go stale if the process is killed, so you need an age check.
Exercise
Your hourly job has timeout 90m around the agent and uses flock -n with exit 0 on skip. At 03:00 a run starts and hangs. What happens at 04:00 and 05:00, and which two changes make this situation visible and bounded?
Show answer
At 04:00 and 05:00 the new runs fail to get the lock, log a skip, and exit 0, so the scheduler reports success while no work gets done. The hung run holds the lock until the 90-minute timeout kills it at 04:30. After that, the 05:00 run gets the lock and works normally. Because the timeout (90 minutes) is longer than the interval (60 minutes), skips are guaranteed whenever a run is slow. Two fixes: set the timeout below the interval (for example 50 minutes) so a hung run is killed before the next tick, and alert when several consecutive runs are skipped or when no successful run has been recorded recently.