我希望您能帮助我优化和加快我编写的脚本,以便为多个源检索数据。现在,脚本可能需要2-10分钟才能运行,这取决于一天中的时间。
所有的任何帮助都会得到极大的支持。
解释脚本:
我使用foreach循环来运行五个不同的URL,然后每个URL将执行五个POST请求,并将结果数据写入文件。
我所希望的:
为了提高脚本的速度,我希望五个URL中的每一个都位于不同的函数中,然后并行运行这五个函数。
我读过的选项之一是pcntl_fork,它能用来实现我所需要的东西吗?如果没有,还有其他选择吗?
我的脚本:
foreach($urls as $url){
$firmato = file_get_html($url, false, stream_context_create($firmato_request));
if (preg_match('(record totali ([\d]+))', $firmato, $count)) {
$firmato_count = $count[1];
};
$inviato = file_get_html($url, false, stream_context_create($inviato_request));
if (preg_match('(record totali ([\d]+))', $inviato, $count)) {
$inviato_count = $count[1];
};
$positive = file_get_html($url, false, stream_context_create($positive_request));
if (preg_match('(record totali ([\d]+))', $positive, $count)) {
$positive_count = $count[1];
};
$negative = file_get_html($url, false, stream_context_create($negative_request));
if (preg_match('(record totali ([\d]+))', $negative, $count)) {
$negative_count = $count[1];
};
$total = file_get_html($url, false, stream_context_create($default_request));
if (preg_match('(record totali ([\d]+))', $total, $count)) {
$default_count = $count[1];
$other_count = $firmato_count+$inviato_count+$positive_count+$negative_count-$default_count;
};
if ($url == 'http://sourceOne.com/MessageServlet') {
$cacheDir = 'cache/one/';
} elseif ($url == 'http://sourceTwo.com/MessageServlet') {
$cacheDir = 'cache/two/';
} elseif ($url == 'http://sourceThree.com/MessageServlet') {
$cacheDir = 'cache/three/';
} elseif ($url == 'http://sourceFour.com/MessageServlet') {
$cacheDir = 'cache/four/';
} elseif ($url == 'http://sourceFive.com/MessageServlet') {
$cacheDir = 'cache/five/';
}
$cache_file = $cacheDir.'hour_'.sprintf('%02d', $previousHour).'.txt';
$data = '<tr><td>'.sprintf('%02d', $previousHour).':00</td><td>'.$firmato_count.'</td><td>'.$inviato_count.'</td><td>'.$positive_count.'</td><td>'.$negative_count.'</td><td>'.$other_count.'</tr>';
file_put_contents($cache_file, $data);
};发布于 2017-02-21 12:11:34
您可以使用curl_multi http://php.net/manual/en/function.curl-multi-init.php,也可以使用已经编写好的库(如https://github.com/jmathai/php-multi-curl ),但是这些库无论如何都是用curl_multi编写的。
https://stackoverflow.com/questions/42366722
复制相似问题