如何异步运行PHP脚本? [英] How to run a PHP script asynchronously?
问题描述
我创建将通过命令行运行的PHP脚本。作为这个脚本的一部分,有次,我可能需要产卵/ fork一个不同的脚本,可能需要很长的时间才能完成。我不想从完成阻止原始脚本。如果我是用JavaScript这样做,我可以在后台运行AJAX请求。这本质上是什么,我想在这里做。我不需要的时候叉完全知道,只是他们开始和完成自己。
我如何异步运行这些PHP脚本?
的foreach($ lotsOfItems为$项目){
如果($本期特价货品> needsExtraHelp){
//这里开始一些异步进程,并把它传递$项目
}
}
$的PID =阵列();
的foreach($ lotsOfItems为$项目){
如果($本期特价货品> needsExtraHelp){
$ PID = pcntl_fork();
如果($ PID == 0){
//你的孩子
后续代码var_dump($项目);
出口(0); //不要忘记这一个!
}否则如果($ PID == -1){
//未能叉过程
}其他{
//你父
$的PID [] = $ PID;
}
} usleep(100); // $ P从高峰$ pvent CPU
的foreach($的PID为$ PID){
pcntl_waitpid($ PID,$退出code,WNOHANG); // prevents僵尸进程
}
}
I am creating a PHP script that will be run via the command line. As part of this script, there are times where I might need to spawn/fork a different script that could take a long time to complete. I don't want to block the original script from completing. If I were doing this with JavaScript, I could run AJAX requests in the background. That is essentially what I am trying to do here. I don't need to know when the forks complete, just that they start and complete themselves.
How can I run these PHP scripts asynchronously?
foreach ($lotsOfItems as $item) {
if ($item->needsExtraHelp) {
//start some asynchronous process here, and pass it $item
}
}
$pids = array();
foreach ($lotsOfItems as $item) {
if ($item->needsExtraHelp) {
$pid = pcntl_fork();
if ($pid == 0) {
// you're in the child
var_dump($item);
exit(0); // don't forget this one!!
} else if ($pid == -1) {
// failed to fork process
} else {
// you're in the parent
$pids[] = $pid;
}
}
usleep(100); // prevent CPU from peaking
foreach ($pids as $pid) {
pcntl_waitpid($pid, $exitcode, WNOHANG); // prevents zombie processes
}
}
这篇关于如何异步运行PHP脚本?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!