Timeout a function in PHP

后端 未结 7 2017
时光说笑
时光说笑 2020-11-29 07:43

Is there a way to timeout a function? I have 10 minutes to perform a job. The job includes a for loop, here is an example:



        
7条回答
  •  情话喂你
    2020-11-29 07:59

    It depends on your implementation. 99% of the functions in PHP are blocking. Meaning processing will not continue until the current function has completed. However, if the function contains a loop you can add in your own code to interrupt the loop after a certain condition has been met.

    Something like this:

    foreach ($array as $value) {
      perform_task($value);
    }
    
    function perform_task($value) {
      $start_time = time();
    
      while(true) {
        if ((time() - $start_time) > 300) {
          return false; // timeout, function took longer than 300 seconds
        }
        // Other processing
      }
    }
    

    Another example where interrupting the processing IS NOT possible:

    foreach ($array as $value) {
      perform_task($value);
    }
    
    function perform_task($value) {
        // preg_replace is a blocking function
        // There's no way to break out of it after a certain amount of time.
        return preg_replace('/pattern/', 'replace', $value);
    }
    

提交回复
热议问题