问题描述
在一个apcahe服务器,我想运行一个PHP脚本作为cron,它在后台启动一个PHP文件,并在文件启动后退出,不等待脚本完成,因为该脚本将需要大约60分钟完成这个可以做吗?
In a apcahe server i want to run a PHP scripts as cron which starts a php file in background and exits just after starting of the file and doesn't wait for the script to complete as that script will take around 60 minutes to complete.how this can be done?
推荐答案
你应该知道PHP中没有线程。
但是如果你在Unix / linux系统上运行,你可以执行程序并轻松地分离它们。
You should know that there is no threads in PHP.But you can execute programs and detach them easily if you're running on Unix/linux system.
$command = "/usr/bin/php '/path/to/your/php/to/execute.php'";
exec("{$command} > /dev/null 2>&1 & echo -n \$!");
可以做这项工作。让我们解释一下:
May do the job. Let's explain a bit :
exec($command);
执行/ usr / bin / php'/ path / to / your / php / to / execute。 php':您的脚本启动,但Apache会在执行下一个代码之前等待执行结束。
Executes /usr/bin/php '/path/to/your/php/to/execute.php' : your script is launched but Apache will awaits the end of the execution before executing next code.
> /dev/null
会将标准输出(即您的echo,print等)重定向到虚拟文件
will redirect standard output (ie. your echo, print etc) to a virtual file (all outputs written in it are lost).
2>&1
将错误输出重定向到标准输出,在同一个虚拟和不存在的文件中写入。这避免了登录到您的apache2 / error.log例如。
will redirect error output to standard output, writting in the same virtual and non-existing file. This avoids having logs into your apache2/error.log for example.
&
是你的情况下最重要的事情:它会分离执行$ command:so exec )将立即释放您的PHP代码执行。
is the most important thing in your case : it will detach your execution of $command : so exec() will immediatly release your php code execution.
echo -n \$!
将给出您的独立执行的PID作为响应:它将由exec()返回,能够使用它(例如,把这个pid放入数据库,杀了它一段时间后,以避免僵尸)。
will give PID of your detached execution as response : it will be returned by exec() and makes you able to work with it (such as, put this pid into a database and kill it after some time to avoid zombies).
这篇关于PHP中的多线程的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!