Reputation: 55
I have a php script file that runs via cron jobs every 30 seconds and runs for a few minutes. I want to limit it so only a maximum amount of X instances can run at the same time, so if X amount of the script are already running the new launched script would exit and when one or more of the running script finishes the next cron will then be able to launch the script successfully.
I found some info about this but mostly for limiting to only 1 instance, like a mutex. So I was thinking on what solutions I could use to achieve what I need, here are some of the ideas I had:
Im leaning towards using the ps command method since seems to be the easier to code. Does someone knows a better method?
Upvotes: 3
Views: 1105
Reputation: 4715
Using "ps u":
if(ifFirstInstance()==false){
echo "ERROR: script already running.\n";
die;
}
//continue here
function ifFirstInstance(){
$basename = basename($_SERVER['SCRIPT_NAME']);
ob_start();
system("ps u", $return);
$result = ob_get_contents();
ob_end_clean();
$pieces = count(explode($basename, $result));
$pieces--;
if($pieces < 2)
return true;
else
return false;
}
Upvotes: 0
Reputation: 1105
IMO, your best bet would be the ps+grep command.
Both MySQL and pid solutions would work but there's always the chance that the script -for whatever reason- dies before it's finished thus leaving you with a counter that doesn't represent the number of scripts running at any given time.
Upvotes: 0