我有一个用于通过API配置VPS的程序。脚本的核心部分将持续命中API(每5秒,15次),直到API吐出IP地址。执行大约需要30秒。
代码中没有错误,程序以97%的可靠性执行它的功能。
但是如果最终用户变得不耐烦并且点击了,脚本将过早结束并且我的系统会中断。
有没有办法执行一部分php脚本作为后台运行的守护程序?这样,如果用户点击事故,该过程仍会运行? 还是其他一些方法?
脚本:
left
答案 0 :(得分:1)
答案 1 :(得分:0)
你可以尝试将你的curl东西拆分成子进程,然后在父进程中返回。您使用的命令是pcntl_fork()
http://php.net/manual/en/function.pcntl-fork.php
这里有一个示例模型,说明如何执行此操作:只需将您的curl代码放入子进程块(执行sleep()的位置)并查看是否符合您的要求:
<?php
// this variable is here to prove that variables set outside of the
// child process' 'if' block can be accessed
$outsideVariable = "i'm from outside";
// fork starts a copy of this script
$pid = pcntl_fork();
// if the return from pcntl_fork() is -1, things have gone awry
if($pid == -1){
die("could not spawn child process. do some error handling";
}
// this is the code that gets executed in the original 'parent'
// process. you do html output here so the user doesn't have to
// wait for the email to be set.
else if($pid == 0){
print "return to user and stop execution";
return true;
}
// this is the child process, the copy of the process that is
// spawned seperately. you can do your curl
// stuff here.
else {
sleep(10); // simluating execution lag
// let's write to file to confirm the child process is doing
// stuff. we use $outsideVariable to show that this process
// can access stuff from the scope of the parent.
$fp = fopen("/tmp/foo","a");
fwrite($fp, "chil pid $pid $outsideVariable \n");
}
?>