PHP set timeout for script with system call, set_time_limit not working

前端 未结 4 1385
遇见更好的自我
遇见更好的自我 2020-12-10 08:45

I have a command-line PHP script that runs a wget request using each member of an array with foreach. This wget request can sometimes take a long time so I want to be able t

4条回答
  •  不知归路
    2020-12-10 09:21

    You can use a combination of "--timeout" and time(). Start off by figuring out how much time you have total, and lower the --timeout as your script runs.

    For example:

    $endtime = time()+15;
    foreach( $url as $key => $value){
      $timeleft = $endtime - time();
      if($timeleft > 0) {
        $wget = "wget -t 1 --timeout $timeleft $otherwgetflags $value";
        print "running $wget
    "; system($wget); } else { print("timed out!"); exit(0); } }

    Note: if you don't use -t, wget will try 20 times, each waiting --timeout seconds.

    Here's some example code using proc_open/proc_terminate (@Josh's suggestion):

    $descriptorspec = array(
       0 => array("pipe", "r"),
       1 => array("pipe", "w"),
       2 => array("pipe", "w")
    );
    $pipes = array();
    
    $endtime = time()+15;
    foreach( $url as $key => $value){
      $wget = "wget $otherwgetflags $value";
      print "running $wget\n";
      $process = proc_open($wget, $descriptorspec, $pipes);
      if (is_resource($process)) {
        do {
          $timeleft = $endtime - time();
          $read = array($pipes[1]);
          stream_select($read, $write = NULL, $exeptions = NULL, $timeleft, NULL);
          if(!empty($read)) {
            $stdout = fread($pipes[1], 8192);
            print("wget said--$stdout--\n");
          }
        } while(!feof($pipes[1]) && $timeleft > 0);
        if($timeleft <= 0) {
          print("timed out\n");
          proc_terminate($process);
          exit(0);
        }
      } else {
        print("proc_open failed\n");
      }
    }
    

提交回复
热议问题