Skip to content

Instantly share code, notes, and snippets.

@codegenin
Last active September 9, 2015 16:30
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save codegenin/c8966d84de6ff4736aee to your computer and use it in GitHub Desktop.
Save codegenin/c8966d84de6ff4736aee to your computer and use it in GitHub Desktop.
Prevent multiple crons running by creating a lock file and time limit
<?php
$filename = "myscript.lock";
$lifelimit = 120; // in Second lifetime to prevent errors
/* check lifetime of file if exist */
if(file_exists($filename)){
$lifetime = time() - filemtime($filename);
}else{
$lifetime = 0;
}
/* check if file exist or if file is too old */
if(!file_exists($filename) || $lifetime > $lifelimit){
if($lifetime > $lifelimit){
unlink($filename); //Suppress if exist and too old
}
$file=fopen($filename, "w+"); // Create lockfile
if($file == false){
die("file didn't create, check permissions");
}
/* Your process */
unlink($filename); //Suppress lock file after your process
}else{
exit(); // Process already in progress
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment