research/stopping-a-scheduled-job-from-running-twice

Stopping a Scheduled Job From Running Twice: A Lock File, a PID Check and flock, Tested in Node.js

Engineering Note · November 30, 2026 · 9 minute read · Node.js · Scheduled Jobs · Reliability · Linux

To stop a scheduled job from running twice at once, take a lock that only one process can hold and exit if you cannot get it. We tested four ways with a small Node.js reminder job. Without a lock, two overlapping runs sent every reminder twice. Checking whether a lock file exists and then writing it let more than one of 20 simultaneous processes through in all 50 rounds we ran. Opening the lock file with Node’s 'wx' flag let exactly one through every round. A plain lock file outlived a crashed run and blocked every run after it; a PID check fixed that, and flock(1) avoided the problem: once the job was killed, its lock was gone. None of them stopped a crashed run’s work from being repeated, which needs a separate fix.

Everything below was run on Linux 6.18 with Node.js 22.23.5 and flock from util-linux 2.39.3. The outputs are real; we removed the shell’s job-control lines (such as [1]+ Done) from them.

Why would a scheduled job run twice?

A nightly or hourly job usually finishes long before its next start. Then one day it does not: an email API is slow, the list is longer than usual, or a retry loop waits. The scheduler starts the next run on time, and now two copies are working through the same list.

Other causes are just as ordinary. Someone runs the job by hand to test it while the scheduled copy is running. A deploy restarts a server that also runs a timer. Two machines both have the same cron line after a migration.

For many jobs the result is double work. For a job that sends emails, charges cards or posts to social media, the result is customers getting things twice.

What did we test with?

A job that “sends” a reminder for every booking not yet reminded, then marks them all as reminded. Each send waits 300 ms to stand in for an email API call and appends a line to sent.log. The bookings file starts with five unreminded customers.

const bookings = JSON.parse(fs.readFileSync(DB, 'utf8'));
const due = bookings.filter(b => !b.reminded);
for (const b of due) {
  await sleep(300);                         // pretend to call an email API
  fs.appendFileSync(SENT, `${id} -> ${b.email}\n`);
}
const now = JSON.parse(fs.readFileSync(DB, 'utf8'));
for (const b of now) if (due.some(d => d.id === b.id)) b.reminded = true;
fs.writeFileSync(DB, JSON.stringify(now));

The mode argument picks the locking strategy, and the job calls acquire() before any work.

What happens with no lock?

We started run A, waited half a second, and started run B:

A: started (pid 933)
B: started (pid 941)
A: sent 5 reminders
B: sent 5 reminders
emails sent: 10
      2 customer1@example.com
      2 customer2@example.com
      2 customer3@example.com
      2 customer4@example.com
      2 customer5@example.com

B read the bookings before A had marked anything, so it saw all five as due. Every customer got two reminders.

Is “check if the lock file exists” enough?

The first lock most people write looks like this:

if (fs.existsSync(LOCK)) { console.log(`${id}: another run holds ${LOCK}; exiting`); return false; }
fs.writeFileSync(LOCK, String(process.pid));
return true;

With runs started half a second apart, it works. But there is a gap between the check and the write, and two processes that arrive close together can both pass the check. Starting processes from a shell staggers them enough to hide the gap, so we wrote a separate test: 20 processes each spin until the same start instant, then try once to take the lock. We counted the winners in each of 50 rounds.

The second version does the check and the create in one call. Node’s 'wx' flag is documented as “Like 'w' but fails if the path exists,” and maps to O_CREAT | O_EXCL:

try { fs.closeSync(fs.openSync(lock, 'wx')); won = true; } catch (e) { if (e.code !== 'EEXIST') throw e; }

Real output:

exists: 50 rounds of 20 processes, rounds with more than one winner: 50, winners in total: 198
wx: 50 rounds of 20 processes, rounds with more than one winner: 0, winners in total: 50

The exists-then-write lock let about four processes through per round, in every round. The 'wx' lock let exactly one through, every time. In the reminder job, the 'wx' version behaved as intended:

A: started (pid 963)
B: another run holds ./job.lock; exiting
A: sent 5 reminders
emails sent: 5

What happens to the lock file when the job crashes?

The 'wx' job removes its lock at the end and in a SIGTERM handler. We checked the handler: after kill -TERM mid-run, no lock file was left. Then we used kill -9, which a process cannot catch, the same way an out-of-memory kill or a power cut ends a process:

A: started (pid 999)
lock file left: 999
B: another run holds ./job.lock; exiting
C: another run holds ./job.lock; exiting

The lock file still named the dead process, and every later run saw it and quit. A job like this stops running without an error, which is the worst way for it to fail. Our note on heartbeat checks for scheduled jobs covers how to notice a job that did not run.

Does a PID check fix the stale lock?

The lock file already holds the process ID of the run that took it. Node’s process.kill(pid, 0) sends no signal; the documentation says signal 0 “can be sent to test for the existence of a process” and throws if it does not exist. EPERM means it exists but belongs to another user, so we treat that as alive:

const pid = Number(fs.readFileSync(LOCK, 'utf8'));
let alive = true;
try { process.kill(pid, 0); } catch (err) { alive = err.code === 'EPERM'; }
if (!alive) {
  console.log(`${id}: lock held by pid ${pid}, which is not running; taking it over`);
  fs.unlinkSync(LOCK);
  return acquire();
}

After kill -9 mid-run:

A: started (pid 1032)
sent before kill: 2
B: lock held by pid 1032, which is not running; taking it over
B: started (pid 1042)
B: sent 5 reminders
emails sent total: 7

The job recovered. Two things are worth knowing. Process IDs are reused, so a stale lock can name a process that is alive but unrelated, and the job will wait for it. And the takeover itself, read then delete then create, has the same kind of gap as the exists check if two runs find the stale lock at once. We did not test that race.

What does flock do differently?

flock(1) from util-linux manages flock(2) locks from the shell: it opens a lock file (creating it if needed), locks it and runs your command while holding it. The lock belongs to the open file, not to the file’s existence. We could not open the flock(2) manual page from this environment, so the tests below are our evidence for what happens when the holder dies. With -n, flock fails instead of waiting, with exit status 1 by default.

flock -n job.flock node job.mjs none A

The job itself uses no lock of its own here (mode none); flock does the locking. Two overlapping runs:

A: started (pid 16814)
B exit code: 1
A: sent 5 reminders
emails sent: 5

Then we killed the Node process with kill -9 and started the next run straight away:

A: started (pid 16912)
killing node pid 16912
B: started (pid 16923)
B: sent 5 reminders
B exit code: 0; emails sent total: 7

No stale lock, no PID check. The job.flock file stays on disk, and that is fine: its presence means nothing, only a held lock does.

We also killed the flock wrapper itself, with kill -9, while the job was running. The command inherits the locked file, so the job kept the lock:

A: started (pid 16870)
B exit code: 1
A: sent 5 reminders
C: started (pid 16880)
C: sent 0 reminders
C exit code: 0

B was refused while A was still working, and C ran normally once A finished. The manual page notes that -o closes the lock before running the command, for a command whose child processes should not hold it. Without -o, a background process the job leaves running keeps the lock too.

A scheduler or monitoring script can tell “skipped because busy” apart from a real failure by choosing the exit code with -E:

== flock -E 75
exit code: 75

Why did every crash still send duplicates?

Look at the totals after each crash: 7 emails for 5 customers, with every lock that recovered. The killed run had sent two reminders but died before marking anything as reminded, so the next run sent all five again:

A -> customer1@example.com
A -> customer2@example.com
B -> customer1@example.com
B -> customer2@example.com
B -> customer3@example.com
B -> customer4@example.com
B -> customer5@example.com

A lock answers “is another run working right now?” It cannot answer “what did the last run finish?” That needs the job to record each item as done right after it handles it, or an idempotency key the email service can use to drop repeats. Our note on idempotency keys for a booking form covers that second idea, and atomic file writes in Node.js covers saving the “done” state so a crash does not corrupt it.

Which should you use?

ApproachStops overlapAfter a crashNotes
No lockNoNot applicableEvery overlap repeats the work
existsSync then writeNo, under close timingLock file stays, job stops runningMore than one winner in 50 of 50 rounds
openSync(lock, 'wx')YesLock file stays, job stops runningNeeds cleanup or a PID check
'wx' plus PID checkYesRecoversPID reuse; untested takeover race
flock -nYesRecoversLinux and similar; one machine only

On a single Linux server, wrap the command in flock -n and choose an exit code with -E. Inside a Node.js program that must lock itself, use 'wx' with a PID check. In both cases, make the work itself safe to repeat.

Limitations

  • Everything ran on one Linux machine with a local file system. File locks over network file systems, on macOS or on Windows can behave differently, and we did not test them.
  • A lock on one machine does nothing for two machines running the same job. That needs a shared lock, such as a database row, which we did not test here.
  • The race test used 20 processes in 50 rounds. It showed the exists check fails often and 'wx' held for those rounds; it does not prove 'wx' can never fail.
  • We did not test the race when two runs find a stale lock at the same moment, or PID reuse, which is rare and hard to set up on purpose.
  • Crashes were simulated with kill -9. We did not test a machine losing power, where the lock file and the job’s own state may be in a different condition afterwards.

Sources

Frequently asked questions

How do I stop a cron job from running twice at the same time?

Take a lock at the start of the job and exit if another run holds it. On Linux, wrapping the command in flock -n with a lock file is the simplest option: in our test the lock was gone as soon as a killed job died, so the next run started normally. In Node.js, opening a lock file with the 'wx' flag works too, but you then need to handle a lock left behind by a crashed run.

Is checking whether a lock file exists good enough?

No. Checking with fs.existsSync and then writing the file leaves a gap between the two steps, and two processes can both pass the check. In our test with 20 processes starting at the same moment, more than one got through in every one of 50 rounds. Opening the file with the 'wx' flag does the check and the create in one step, and exactly one process won every round.

What happens to a lock file when the job crashes?

It stays on disk, because nothing removes it. In our test, after killing the job with SIGKILL, every later run saw the lock and exited, so the job would never run again until someone deleted the file. A SIGTERM handler can remove it on a normal stop, but nothing runs on SIGKILL or a power cut.

How does flock handle a crashed job?

flock(1) holds a lock on an open file rather than relying on the file existing. In our test, after killing the job with SIGKILL, the next run started at once. When we killed only the flock wrapper, the job kept running and still held the lock, so a second run was refused until the job finished.

Does a lock stop a crashed job from repeating work?

No. A lock stops two runs from overlapping; it does not know what a crashed run already did. In our test the killed run had sent two of five reminders, and the next run sent all five, so two customers got the reminder twice. Mark each item as done right after it is handled, or use an idempotency key, so a rerun skips finished work.

More from Research

← All research