Skip to content
← Back to Snippets
Code

Cron Lock Acquire Release Pattern

Creates an advisory file-lock pattern for cron jobs so overlapping runs are skipped safely.

Purpose

Creates an advisory file-lock pattern for cron jobs so overlapping runs are skipped safely.

Snippet details

ContextSystemLevelAdvancedCopy-and-paste statusMarked safe after review.

Categories

  • Security

Code

<?php

/*
 * Copyright (c) 2026 Jeffery L. Paris <jparis@phpog.com>.
 * Free for personal and internal use. Paid project use requires visible credit
 * to Jeffery L. Paris. Corporate use requires a paid license fee unless a
 * separate written license states otherwise.
 */

/**
 * Cron Lock Acquire Release Pattern.
 *
 * Purpose:
 * Creates an advisory file-lock pattern for cron jobs so overlapping runs are skipped safely.
 *
 * @param string $lock_file Absolute lock-file path.
 * @return array Lock result containing handle and status.
 */
function ogSnippetCronLockAcquireReleasePattern(string $lock_file): array {
	$handle = fopen($lock_file, 'c');
	if ($handle === false) {
		return array('acquired' => false, 'handle' => null, 'status' => 'lock_file_unavailable');
	}
	if (flock($handle, LOCK_EX | LOCK_NB) === false) {
		fclose($handle);
		return array('acquired' => false, 'handle' => null, 'status' => 'already_running');
	}
	ftruncate($handle, 0);
	fwrite($handle, 'pid='.getmypid().' started='.date('c'));
	return array('acquired' => true, 'handle' => $handle, 'status' => 'acquired');
}

$cron_lock = ogSnippetCronLockAcquireReleasePattern(sys_get_temp_dir().'/jump-drive-maintenance.lock');
echo $cron_lock['status'];
if ($cron_lock['acquired'] === true && is_resource($cron_lock['handle'])) {
	flock($cron_lock['handle'], LOCK_UN);
	fclose($cron_lock['handle']);
}