Skip to content

Instantly share code, notes, and snippets.

@egulhan
Created March 19, 2014 20:02
Show Gist options
  • Save egulhan/9650029 to your computer and use it in GitHub Desktop.
Save egulhan/9650029 to your computer and use it in GitHub Desktop.
Script locking mechanism for one-time-running scripts such as cron scripts
<?php
/**
* Class Lock
* Script locking mechanism for one-time-running scripts.
*/
class Lock
{
private $fp;
function __construct()
{
$this->fp=fopen(__FILE__,'r');
if (!flock($this->fp,LOCK_EX|LOCK_NB))
die(sprintf('[%s] The script %s has already been running. Terminated!',date('Y-m-d H:i:s'),basename(__FILE__)));
}
function __destruct()
{
flock($this->fp,LOCK_UN);
fclose($this->fp);
}
}
?>
<?php
/**
* This script runs one time at a time.
*/
require_once('Lock.php');
$scriptLock=new Lock();
?>
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment