New Tool Radar

AI Agents & Automation

How to Prevent Overlapping Scheduled Agent Runs of the Same Task

Prevent overlapping scheduled agent runs so the same task never runs twice at once.

Schematic with three steps: Take a lock for the task when; Skip the next run while the lock; Release the lock when the run ends,.

A scheduled run that takes longer than its interval will overlap with the next scheduled run, and two copies of the same task running at once can double-write, double-send, or double-charge. Overlap prevention is a lock: when a run starts, it takes the lock for its task, and the next scheduled run checks the lock first. If the lock is held, the new run skips itself and logs the skip, instead of starting. Zapier’s schedule trigger runs an agent at set intervals, which is exactly the shape where a slow run meets its own next start. Set the lock before the work starts and release it when the run ends, whatever the outcome.

What you need

  • A scheduled agent run whose duration can exceed its interval
  • A lock per task, held while the run executes and released when it ends
  • A named outcome for a skipped run: log the skip and tell the owner

Step 1: Take a lock for the task when the run starts

At the start of each run, take a lock named for the task, with the run id and start time recorded. A lock taken after the work starts does not prevent overlap.

Step 2: Skip the next run while the lock is held

When the next scheduled start arrives, check the lock first. If it is held, skip that run, log the skip with the run id, and tell the owner. Never start a second copy.

Step 3: Release the lock when the run ends, whatever the outcome

Release the lock when the run finishes, fails, or is cancelled, so the next scheduled run can start. A lock that is never released is a task that never runs again.

Worked example: synthetic cron overlap check

The table below is a synthetic example. It shows the expected result of overlap prevention; no runs overlapped.

Check Expected Result
First run takes the lock Yes Pass
Second start sees the lock Yes Pass
Second run skips and logs Yes Pass
Lock released at the end Yes Pass

Expected result (UNTESTED). the first run holds the lock, the second start skips and logs the skip, and the lock is released when the run ends. This check was not run live; the table shows the expected result for the synthetic example.

Limits

  • A lock that is never released blocks the task forever, so give it an expiry as a backstop.
  • The lock must be visible to every worker, or two workers can each think they hold it.
  • Skipping a run means its work is missed, so tell the owner when a skip happens.
  • A lock prevents overlap, not slowness: a run that always overruns needs a longer interval.

Sources

See all