PHP/Cron Limit Number of Concurrently Running Scripts
I have a script written in PHP that is kicked off by a cron job. It's a long running script, and often cron kicks off another instance before the last is finished. That's fine. I allow 3 instances of this script to run at any given time.
I limit the script to 3 instances with this code at the top of the script:
exec('ps -A | grep nameofmyscript', $results);
if (count($results) > 4) {
开发者_如何学编程 echo "Already Running\n"
die(0);
}
It works, but I'm looking for a better way. This approach backfired on me a few weeks back when I renamed the script, and forgot to change that line of code. It also fails when the script is named something similar to an already running process.
Using PHP, you could create a randomly named lock file in a directory specific to the cron job. Check for the number of lock files that exist in the directory before letting the PHP script continue. This may not be the best solution though.
You could automate the name placement...
exec('ps -A | grep ' . escapeshellarg(basename(__FILE__)) , $results);
if (count($results) > 4) {
echo "Already Running\n"
die(0);
}
精彩评论