我需要做的是使用PHP处理数据库中待处理的多个请求。
我目前正在尝试做的是:
当我的cronjob运行时。我想立即调用文件“process_a.php” 10次,而不必等待它完成处理(process_a.php可能要花几分钟时间)。
我尝试使用CURL做到这一点。但是恰好在我的cronjob调用process_a.php时,它等待它完成处理并返回,然后再调用另一个process_a.php文件。
我什至尝试将代码放入process_a.php中以立即关闭连接,然后在后台继续处理。但是cronjob仍在等待它完成。
我只希望同一文件一次执行10次,就像10个不同的用户请求我的网站的index.php页面一样。
有任何想法吗!?
最佳答案
正如@Brad所说,curl-multi-exec应该是一个选项。
http://php.net/manual/en/function.curl-multi-exec.php
<?php
//create the multiple cURL handle
$mh = curl_multi_init();
// create both cURL resources
for($i = 0; $i < 10;$i++){
$ch[$i] = curl_init();
curl_setopt($ch[$i], CURLOPT_URL, "http://urhost//path/to/process_a.php");
curl_setopt($ch[$i], CURLOPT_HEADER, 0);
curl_multi_add_handle($mh,$ch[$i]);//add the handles
}
$active = null;
//execute the handles
do {
$mrc = curl_multi_exec($mh, $active);
} while ($mrc == CURLM_CALL_MULTI_PERFORM);
while ($active && $mrc == CURLM_OK) {
if (curl_multi_select($mh) != -1) {
do {
$mrc = curl_multi_exec($mh, $active);
} while ($mrc == CURLM_CALL_MULTI_PERFORM);
}
}
//close the handles
for($i = 0; $i < 10;$i++){
curl_multi_remove_handle($mh, $ch[$i]);
}
curl_multi_close($mh);
?>
我通过调用下面的另一个脚本来测试此脚本:
<?php
print microtime();//Return current Unix timestamp with microseconds
print '<br>';
?>
这是结果,每个句柄的执行时间相差微秒。
0.27085300 1340214659
0.44853600 1340214659
0.46611800 1340214659
0.48201000 1340214659
0.50209400 1340214659
0.48233900 1340214659
0.52274300 1340214659
0.54757800 1340214659
0.57316900 1340214659
0.59475800 1340214659
关于php - 使用CURL与cronjob进行PHP多处理,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/11108317/