<?php
function runIfNotLocked(string $lockFile, callable $job): bool {
$fh = fopen($lockFile, 'c');
if (!$fh) throw new RuntimeException("Cannot open $lockFile");
if (!flock($fh, LOCK_EX | LOCK_NB)) {
fclose($fh);
return false; // another instance is already running
}
try {
$job();
return true;
} finally {
flock($fh, LOCK_UN);
fclose($fh);
}
}
$ran = runIfNotLocked('/tmp/myjob.lock', function () {
// Expensive cron task — runs only when no other copy holds the lock.
});
if (!$ran) error_log('myjob: skipped — another instance is running');
Create a free account and build your private vault. Share publicly whenever you want.