PHP 中的多线程 [英] Multi threading in PHP

查看:28
本文介绍了PHP 中的多线程的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

在 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); 

Executes/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

会将标准输出(即您的回显、打印等)重定向到一个虚拟文件(写入其中的所有输出都将丢失).

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 的执行:因此 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 中的多线程的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆