Skip to content

Instantly share code, notes, and snippets.

@RandomArray
Last active February 15, 2016 00:33
Show Gist options
  • Save RandomArray/668411daa88ca8271f3c to your computer and use it in GitHub Desktop.
Save RandomArray/668411daa88ca8271f3c to your computer and use it in GitHub Desktop.
Delays the next execution of the script by storing the next execution time in file and checking against it before continuing.
<?php
// Random time delay before next execution.
// Stores the next time in a file.
// Time is read from this file and compared against current time.
// If time has passed, perform another random delay between 1-59 seconds before execution.
$timeFile = 'nexttime.txt';
// $timeFile = dirname(__FILE__).'/nexttime.txt'; // Use this line for when running from CRON.
$minDelayMins = 1;
$maxDelayMins = 5;
if(!file_exists($timeFile)){
// Write new time to new file if file does not exist
$newTimeDelay = writeNewTimeDelay();
echo $timeFile.' does not exist. Created a new file with delay set to '.$newTimeDelay.' seconds from now.'.PHP_EOL;
}
$nextTime = file_get_contents($timeFile);
if(time()>=$nextTime){
// Enough time has elpased, run the script
echo 'TIME TO RUN...'.PHP_EOL;
// Sleep for a randomly throughout the minute for randomization of execution time down to the second.
$microsleep = rand(1000000,59000000); // 1 second <> 59 seconds
echo 'PAUSING FOR '.($microsleep/1000000).' SECONDS'.PHP_EOL;
usleep($microsleep);
echo 'RUNNING!!!!!'.PHP_EOL;
///////////////////
// Do Stuff Here //
///////////////////
// Write new time to file
$newTimeDelay = $newTimeDelay = writeNewTimeDelay();
echo 'New delay set to '.$newTimeDelay.' seconds from now.'.PHP_EOL;
}else{
// Not time to run yet.. exit
$seconds = ($nextTime - time());
$timeRemain = getMins($seconds);
echo 'Not time yet.. '.$timeRemain.' ('.$seconds.' seconds) remaining'.PHP_EOL;
}
function writeNewTimeDelay(){
$newTimeDelay = ( time() + rand($GLOBALS['minDelayMins']*60, $GLOBALS['maxDelayMins']*60) ) ; // Now plus a minimum of 30 min, max 5 minutes (60*5)
file_put_contents($GLOBALS['timeFile'], $newTimeDelay);
return ( $newTimeDelay - time() ); // Return seconds of a delay
}
function getMins($t){
return sprintf("%02d%s%02d", ($t/60)%60, ':', $t%60);
}
?>
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment