How to check if a PHP script is running

How to create a continuous while loop, if it is already running, do not run it again, I assume that if the script is running, it will update the last time cron in the database, and the script checks if the current time is not - 40 seconds less than the last time cron. An example of what I have, but this is an overflow (running process again and again) Thanks!

<?php
ignore_user_abort(1); // run script in background 
set_time_limit(0);    // set limit to 0


function processing()
{
//some function here
setting::write('cron_last_time', $time); // write cron last time to database
}

$time = current_timestamp();  // current time
$time_before = $time - 20;   //

$settings = setting::read('module_cron_email'); // Get last cron time from database ( in array )
$time_last = $settings['setting_value'];     // Last cron time get value from array



if ($time_before < $time_last) // check if time before is less than last cron time
{ 
   do{
   processing(); //run our function
   sleep(7);    // pause for 7 seconds
   continue;   // continue
   }
   while(true); // loop
}else{

echo "already running";
die();
}
?> 
+3
source share
3 answers

When running the script, check the lock file. If it exists, close or skip the loop. If it does not exist, create a file and let it run.

+5
source

Just add the following to the top of the script.

    <?php
    // Ensures single instance of script run at a time.
    $fileName = basename(__FILE__);
    $output = shell_exec("ps -ef | grep -v grep | grep $fileName | wc -l");
    //echo $output; 
    if ($output > 2)
    {
        echo "Already running - $fileName\n";
        exit;   
    }   

    // Your PHP  code.
?>
+1
source

PHP PCNTL is what you need! You can use PHP processes for it.

                 while(true) { // Infinite

                     $pid = pcntl_fork();

                        switch (pcntl_fork($pid)) {

                                case -1:

                                        die('Fork failed');

                                        break;

                                case 0: // Child

                                        processing();

                                        exit(0);

                                        break;

                                default: // Parent

                                        pcntl_waitpid($pid, $status);

                                        break;

                        }

        }
-2
source

All Articles