Prevent Concurrent Cron Jobs Using `flock`

Search for a command to run...

No comments yet. Be the first to comment.
Most AI agents that support scheduled tasks have two sources of instruction when a cron job fires: The cron prompt — the task-specific instructions you wrote when scheduling the job The skill — a re

TL;DR Scarp draw result, host on GitHub, retrieve it like API at damacai.hongineer.com. Data Scraping I have previously shared a technique for scraping Da Ma Cai draw result. Now I finally have time t

This is a Bash script that check if the replica (slave) health status. If there is an issue, it will exist with non-zero status. This is useful when used with monitoring tools like [Monit](https://mmo

chmod is a command-line utility used to change the access permissions of file system objects such as files and directories. It allows you to control who can read, write, and execute those objects. Changing Permissions Using Octal Notation Example Usa...
chown changes the ownership of files and directories. This involves modifying the user and/or group associated with a file, determining who has access and permissions. Changing File Ownership to a Specific User Example Usage: chown user file.txt What...
flock is a utility in Unix-like operating systems (like Linux) used for advisory file locking. Its primary purpose is to prevent multiple instances of a script or process from concurrently accessing and potentially corrupting a shared file or resource.
Here's a breakdown of what flock is and why it's important:
Imagine you have a shell script that updates a log file or a configuration file. If this script is run by multiple processes simultaneously (e.g., from different cron jobs, or by multiple users), you could run into a "race condition":
This can lead to data loss, corruption, or unpredictable behavior.
flock Solves This: Advisory Locksflock addresses this by implementing advisory locks. Here's how it works:
flock.-x or default): Only one process can hold an exclusive lock on a file at a time. If another process tries to acquire an exclusive lock while one is held, it will either wait (default behavior) or fail immediately (-n, non-blocking). This is typically used for write operations.-s): Multiple processes can hold a shared lock on a file simultaneously. However, no process can hold an exclusive lock while a shared lock is active, and vice versa. This is typically used for read operations where multiple readers are fine, but a writer needs exclusive access.-u.flock provides advisory locking. This means the operating system doesn't force processes to obey the lock. For flock to be effective, all processes that access the shared resource must explicitly use flock to acquire a lock before accessing the resource. If a process ignores flock, it can still read or write the file, potentially leading to corruption.Preventing Concurrent Cron Jobs: A very common use case is to ensure that a cron job doesn't run on top of itself if a previous instance is still running.
#!/bin/bash
LOCKFILE="/var/lock/my_script.lock"
# Try to acquire an exclusive, non-blocking lock.
# If the lock is already held, exit immediately (do not run).
exec 200>$LOCKFILE
flock -n 200 || exit 1
# If we reached here, the lock was acquired.
echo "Script started at $(date)" >> /var/log/my_script.log
# Simulate some work that takes time
sleep 30
echo "Script finished at $(date)" >> /var/log/my_script.log
# The lock is automatically released when the script exits,
# because file descriptor 200 is closed.
flock can operate on a file path directly or, more commonly, on an open file descriptor (like in the example above, where exec 200>$LOCKFILE opens the lock file on file descriptor 200). Operating on a file descriptor is often preferred because the lock is tied to the descriptor and automatically released when the descriptor is closed (e.g., when the script exits), even if the script crashes.In summary, flock is a fundamental tool for managing concurrent access to shared resources in shell scripting, providing a cooperative mechanism to maintain data integrity and system stability.
Thanks for making it this far 😉. Systemd timer is encouraged over cron job. If a timer is still running when the next scheduled trigger comes up, it will not start a second instance. Therefore flock is not needed here.