FAQ   •  Поиск
Вход  •  Регистрация
 
Параллельные процессы в PHP с Apache

 
Начать новую тему   Ответить на тему    Список форумов newssoft.ru -> PHP
Предыдущая тема :: Следующая тема  
Автор Сообщение
admin
Site Admin


Зарегистрирован: 11.09.2008
Сообщения: 546

СообщениеДобавлено: Пт Янв 10, 2020 6:17 pm    Заголовок сообщения: Параллельные процессы в PHP с Apache Ответить с цитатой

Выполнение параллельного процесса в PHP-скрипте с контролем времени:

Код:

<?
echo date('H:i:s')."<br />";
$domain = 'domain1254';
$zone = 'com';


$descriptorspec = array(
   0 => array("pipe", "r"),  // stdin is a pipe that the child will read from
   1 => array("pipe", "w"),  // stdout is a pipe that the child will write to
   2 => array("file", "error-output.txt", "a") // stderr is a file to write to
);
$cwd = './';
$env = array(lookupResult => '');
$process = proc_open('php', $descriptorspec, $pipes, $cwd, $env);

if (is_resource($process)) {
    // $pipes now looks like this:
    // 0 => writeable handle connected to child stdin
    // 1 => readable handle connected to child stdout
    // Any error output will be appended to /tmp/error-output.txt

   fwrite($pipes[0], '<?php '.
   'session_start(); '.
   'require_once("_rootconfig.php"); '.
   'global $include_path, $domain, $zone; '.
   'include $include_path."/newfunctions.php"; '.
   '$whoiseMaster1 = $include_path."2/whois-master/Domaintools.php"; '.
   'if(file_exists($whoiseMaster1)) require_once($whoiseMaster1); '.
   'else exit("cannot lookup selected domains"); '.
   'unset($whoiseMaster1); '.
   '$lookup = new Domaintools(); '.
   '$_ENV["lookupResult"] = $lookup->whois("'.$domain.'", "'.$zone.'"); '.
   'print_r($_ENV); '.
   '?>');
   
    /*
    fwrite($pipes[0], '<?php '.
   'session_start(); '.
   'require_once("_rootconfig.php"); '.
   'global $include_path; '.
   'include $include_path."/newfunctions.php"; '.
   '$domain = iconv("UTF-8", "windows-1251", "'.$domain.'"); '.
   '$zone = iconv("UTF-8", "windows-1251", "'.$zone.'"); '.
   '$d2 = new domain($domain.".".$zone); '.
   'unset($d2->servers); '.
   '$_ENV["lookupResult"] = array("domain" => $domain, "zone" => $zone); '.
   'if($d2->is_available()) { '.
   '   if($d2->last_error != "") { '.
   '      if($d2->my_whois_server != "") { '.
   '         $_ENV["lookupResult"]["status"]=$d2->last_error; '.
   '         $_ENV["lookupResult"]["code"]=-4; '.
   '      } '.
   '      if(strpos($d2->last_error,"Query rate of")) { '.
   '         $_ENV["lookupResult"]["status"]="error"; '.
   '         $_ENV["lookupResult"]["code"]=-3; '.
   '      } '.
   '      $isDomainOnlyLatin1 = (preg_match("/^[\w\d\s.,-]*$/", $domain))?true:false; '.
   '      $isZoneOnlyLatin1   = true; '.
   '      if( '.
   '         ($isZoneOnlyLatin1 && !$isDomainOnlyLatin1) || '.
   '         (!$isZoneOnlyLatin1 && $isDomainOnlyLatin1) '.
   '      ) { '.
   '         $_ENV["lookupResult"]["status"]="Domain name not valid"; '.
   '         $_ENV["lookupResult"]["code"]=-2; '.
   '      } '.
   '      if(strlen($domain)<2) { '.
   '         $_ENV["lookupResult"]["status"]="Domain name to short"; '.
   '         $_ENV["lookupResult"]["code"]=-1; '.
   '      } '.
   '   } else { '.
   '      if($d2->premium_domain) { '.
   '         $_ENV["lookupResult"]["status"]="premium"; '.
   '         $_ENV["lookupResult"]["code"]=2; '.
   '      } else { '.
   '         $_ENV["lookupResult"]["status"]="success"; '.
   '         $_ENV["lookupResult"]["code"]=1; '.
   '      } '.
   '   } '.
   '} else { '.
   '   $_ENV["lookupResult"]["status"]="warning"; '.
   '   $_ENV["lookupResult"]["code"]=0; '.
   '} '.
   'print_r($_ENV); '.
   '?>');
   */
    fclose($pipes[0]);

    for( $ic = 5; $ic > 0; $ic-- ) {
        echo "check, wait $ic seconds...<br />";
        sleep(1);
    }
    $etat = proc_get_status($process);
   // It is important that you close any pipes before calling
   // proc_close in order to avoid a deadlock
    if($etat['running'] == true) {
        echo "To long wait...<br />";
        fclose($pipes[1]);
        $return_value = proc_terminate($process);
    } else {
        echo "Complete intime...<br />";
        $arrresult = stream_get_contents($pipes[1]);
        fclose($pipes[1]);
        $return_value = proc_close($process);
    }
    //echo "command returned $return_value<br />";
   
    foreach(explode("[", trim(trim(trim(trim($arrresult, "Array")), "()"))) as $key => $val) {
        $tvar = explode("] => ", trim($val));
      if(!empty($tvar[1])) $arrresult2[$tvar[0]] = $tvar[1];
    }
    unset($arrresult2["lookupResult"]);
   $arrresult2["code"] = trim(trim($arrresult2["code"], ") "));
   $lookupResult = $arrresult2;
   unset($arrresult);
   unset($arrresult2);

}
echo "<br />".date('H:i:s')."<br />";
?>


[Ссылки]
1: Асинхронное параллельное исполнение в PHP
2: proc_open
3: stream_get_contents
Вернуться к началу
Посмотреть профиль Отправить личное сообщение Отправить e-mail
admin
Site Admin


Зарегистрирован: 11.09.2008
Сообщения: 546

СообщениеДобавлено: Пт Янв 10, 2020 8:32 pm    Заголовок сообщения: Ответить с цитатой

С помощью pthreads:

Статья
Мануал

Код:

class Request1 extends Thread {
    $username = 'xxxxx';
    $api_onfleet = 'xxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxx';   
    $url_onfleet = "https://onfleet.com/api/v2/tasks";
    public function run() {
        curl_setopt($curl, CURLOPT_SSLVERSION, CURL_SSLVERSION_TLSv1_2);
        $request =  $this->url.'api/mail.send.json';

        // Generate curl request
        $session = curl_init($request);
        // Tell curl to use HTTP POST
        curl_setopt ($session, CURLOPT_POST, true);
       // Tell curl that this is the body of the POST
       curl_setopt ($session, CURLOPT_POSTFIELDS, $params);
       // Tell curl not to return headers, but do return the response
       curl_setopt($session, CURLOPT_HEADER, false);
       curl_setopt($session, CURLOPT_RETURNTRANSFER, true);

        // obtain response
        $response = curl_exec($session);
        curl_close($session);
    }
}


class Request2 extends Thread {
    $username = 'xxxxx';
    $api_onfleet = 'xxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxx';   
    $url_onfleet = "https://onfleet.com/api/v2/tasks";
    public function run() {
      $ch = curl_init();
      curl_setopt($ch, CURLOPT_URL, $url_onfleet);
      curl_setopt($ch, CURLOPT_FOLLOWLOCATION, 1);
      curl_setopt($ch, CURLOPT_RETURNTRANSFER, 1);
      curl_setopt($ch, CURLOPT_SSL_VERIFYPEER, false);
      curl_setopt($ch, CURLOPT_USERPWD, $this->api_onfleet);
      curl_setopt($ch, CURLOPT_HTTPAUTH, CURLAUTH_BASIC);
      curl_setopt($ch, CURLOPT_ENCODING, ""); 
      curl_setopt($ch, CURLOPT_POST, true);
      curl_setopt($ch, CURLOPT_POSTFIELDS, '{"destination":{"address":{"unparsed":"'.$pickup_address.'"},"notes":"'.$comments.'"},"recipients":[{"name":"'.$name.'","phone":"+61'.$phone.'","notes":"Number of riders: '.$riders.'"}],"completeBefore":'.$timestamp.',"pickupTask":"yes","autoAssign":{"mode":"distance"}}');

      $result_pickup = curl_exec($ch);
      curl_close($ch);

      // Post the Dropoff task to Onfleet
      $curl = curl_init();
      curl_setopt($curl, CURLOPT_URL, $this->url_onfleet);
      curl_setopt($curl, CURLOPT_FOLLOWLOCATION, 1);
      curl_setopt($curl, CURLOPT_RETURNTRANSFER, 1);
      curl_setopt($curl, CURLOPT_SSL_VERIFYPEER, false);
      curl_setopt($curl, CURLOPT_USERPWD, $this->api_onfleet);
      curl_setopt($curl, CURLOPT_HTTPAUTH, CURLAUTH_BASIC);
      curl_setopt($curl, CURLOPT_ENCODING, ""); 
      curl_setopt($curl, CURLOPT_POST, true);
      curl_setopt($curl, CURLOPT_POSTFIELDS, '{"destination":{"address":{"unparsed":"'.$dropoff_address.'"},"notes":"'.$comments.'"},"recipients":[{"name":"'.$name.'","phone":"+61'.$phone.'","notes":"Number of riders: '.$riders.'"}],"autoAssign":{"mode":"distance"}}');

      $result_dropoff = curl_exec($curl);
      curl_close($curl);
    }
}

$req1 = new Request1();
$req1->start();
$req2 = new Request2();
$req2->start();
Вернуться к началу
Посмотреть профиль Отправить личное сообщение Отправить e-mail
Показать сообщения:   
Начать новую тему   Ответить на тему    Список форумов newssoft.ru -> PHP Часовой пояс: GMT + 3
Страница 1 из 1

 
Перейти:  
Вы можете начинать темы
Вы можете отвечать на сообщения
Вы не можете редактировать свои сообщения
Вы не можете удалять свои сообщения
Вы не можете голосовать в опросах


Powered by phpBB © 2001, 2005 phpBB Group
AllSat 22  - photographe de mariage - 2006