CertGrid CertGrid
Hands-on Lab·Python Automation for IT

Python Locking and Single-Instance Scripts

A cron job that sometimes takes longer than its interval will eventually run twice at once. The obvious fix - a lock file - has a failure mode that is worse than the problem: a run killed while holding it locks the job out permanently. This guide shows the collision, the stale lock, and fcntl.flock, which the kernel releases when the holder dies no matter how it died.

OS and Process Automation Guide 22 of 39 Intermediate

fcntl is Unix-only and always has been; on Windows the equivalent is msvcrt.locking. unlink(missing_ok=True) needs Python 3.8.

Everything on this page runs on the control node. Any machine with Python 3 will do.
Server NameIP AddressOSRolesCPURAMHDD
RUNNER01192.168.0.27Ubuntu 26.04 LTSControl node - every script in this path runs here2 Core4 GB50 GB

This guide includes

Use this for any job scheduled more often than it reliably finishes. This matters because two copies will eventually overlap - and a lock file left behind by a killed run blocks every run after it, unless the kernel is the one holding the lock.

Before you start

  1. Two runs at once

  2. A lock file claimed without a race

  3. And what happens when a run dies holding it

  4. A lock the kernel releases for you

  5. The file left behind is harmless

  6. Even when the holder is killed

  7. A context manager, so it cannot be forgotten

Official sources