Running a php script via ajax, but only if it is not already running

后端 未结 6 1619
轮回少年
轮回少年 2021-02-13 21:28

My intention is this.

My client.html calls a php script check.php via ajax. I want check.php to check if another script task.php is already being run. If it is, I do not

6条回答
  •  离开以前
    2021-02-13 21:36

    You can get an exclusive lock on the script itself for the duration of the script running

    Any other attempts to run it will end as soon as the lock() function is invoked.

    //try to set a global exclusive lock on the file invoking this function and die if not successful
    function lock(){
      $file = isset($_SERVER['SCRIPT_FILENAME'])?
        realpath($_SERVER['SCRIPT_FILENAME']):
        (isset($_SERVER['PHP_SELF'])?realpath($_SERVER['PHP_SELF']):false);
      if($file && file_exists($file)){
        //global handle stays alive for the duration if this script running
        global $$file;
        if(!isset($$file)){$$file = fopen($file,'r');}
        if(!flock($$file, LOCK_EX|LOCK_NB)){
            echo 'This script is already running.'."\n";
            die;
        }
      }
    }
    

    Test

    Run this in one shell and try to run it in another while it is waiting for input.

    lock();
    
    //this will pause execution until an you press enter
    echo '...continue? [enter]';
    $handle = fopen("php://stdin","r");
    $line = fgets($handle);
    fclose($handle);
    

提交回复
热议问题