php 如何异步运行PHP代码
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/5905877/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
How to run the PHP code asynchronous
提问by AjayR
How can I run PHP code asynchronously without waiting? I have a long run (almost infinite) that should run while server starts and should process asynchronously without waiting.
如何在不等待的情况下异步运行 PHP 代码?我有一个长期运行(几乎无限)应该在服务器启动时运行并且应该异步处理而无需等待。
The possible options I guess are:
我猜可能的选择是:
- Running the code in a web page and keep it open to do that task
- Calling the script from some command line utility (I am not sure how) which would process in the background.
- 在网页中运行代码并保持打开状态以执行该任务
- 从一些命令行实用程序(我不确定如何)调用脚本,这将在后台处理。
I am running the PHP scripts on my local server which will send emails when certain events occur, e.g. birthday reminders.
我在我的本地服务器上运行 PHP 脚本,它会在发生某些事件时发送电子邮件,例如生日提醒。
Please suggest how can I achieve this without opening the page in a browser.
请建议如何在不在浏览器中打开页面的情况下实现此目的。
回答by Todd Chaffee
If you wanted to run it from the browser (perhaps you're not familiar with the command line) you could still do it. I researched many solutions for this a few months ago and the most reliable and simplest to implement was the following from How to post an asynchronous HTTP request in PHP
如果您想从浏览器运行它(也许您不熟悉命令行),您仍然可以这样做。几个月前我为此研究了许多解决方案,最可靠和最简单的实现是以下来自How to post an asynchronous HTTP request in PHP
<?php
$params['my_param'] = $a_value;
post_async('http:://localhost/batch/myjob.php', $params);
/*
* Executes a PHP page asynchronously so the current page does not have to wait for it to finish running.
*
*/
function post_async($url, array $params)
{
foreach ($params as $key => &$val) {
if (is_array($val)) $val = implode(',', $val);
$post_params[] = $key.'='.urlencode($val);
}
$post_string = implode('&', $post_params);
$parts=parse_url($url);
$fp = fsockopen($parts['host'],
isset($parts['port'])?$parts['port']:80,
$errno, $errstr, 30);
$out = "POST ".$parts['path']." HTTP/1.1\r\n";
$out.= "Host: ".$parts['host']."\r\n";
$out.= "Content-Type: application/x-www-form-urlencoded\r\n";
$out.= "Content-Length: ".strlen($post_string)."\r\n";
$out.= "Connection: Close\r\n\r\n";
if (isset($post_string)) $out.= $post_string;
fwrite($fp, $out);
fclose($fp);
}
Let's say the file above is in your web root directory (/var/www
) for example and is called runjobs.php. By visiting http://localhost/runjobs.php
your myjob.php
file would start to run. You'd probably want to add some output to the browser to let you know it was submitted successfully and it wouldn't hurt to add some security if your web server is open to the rest of the world. One nice thing about this solution if you add some security is that you can start the job anywhere you can find a browser.
例如,假设上面的文件位于您的 Web 根目录 ( /var/www
) 中,名为 runjobs.php。通过访问http://localhost/runjobs.php
您的myjob.php
文件将开始运行。您可能希望向浏览器添加一些输出,让您知道它已成功提交,如果您的 Web 服务器对世界其他地方开放,添加一些安全性也无妨。如果您添加一些安全性,此解决方案的一个好处是您可以在任何可以找到浏览器的地方开始工作。
回答by eykanal
Definitely sounds like a job for a cron task. You can set up a php script to do your task once and have the cron run as often as you like. Here'sa good writeup on how to have a php script run as a cron task; it's very easy to do.
绝对听起来像是一项 cron 任务的工作。您可以设置一个 php 脚本来完成一次任务,并让 cron 随心所欲地运行。这是一篇关于如何将 php 脚本作为 cron 任务运行的好文章;这很容易做到。
回答by David Fells
This isn't really what PHP is designed for. You have to use the PECL threading library to spin off threads that run asynchronously, and I don't recommend it. The new hotness in the async department is node.js - I recommend you look into that and see if you can utilize it. It's designed for light weight, asynchronous network operations, and can be used to fire PHP scripts.
这并不是 PHP 的真正设计目标。您必须使用 PECL 线程库来分离异步运行的线程,我不建议这样做。异步部门的新热点是 node.js - 我建议你研究一下,看看你是否可以利用它。它专为轻量级异步网络操作而设计,可用于触发 PHP 脚本。
回答by Magicianeer
How Can I run PHP code asynchronously without waiting. I have a long run (almost inifinite) that should run while server starts and should process asynchrously without waiting.
如何在不等待的情况下异步运行 PHP 代码。我有一个长期运行(几乎无限),它应该在服务器启动时运行并且应该异步处理而无需等待。
Assuming a typical LAMP system, you can start a PHP daemon from the command line with
假设一个典型的 LAMP 系统,你可以从命令行启动一个 PHP 守护进程
root# php yourscript.php &
where yourscript.php contains something similar to
其中 yourscript.php 包含类似于
<?php
$log = fopen('/var/log/yourscript.log', 'a+');
// ### check if we are running already omitted
while(true) {
// do interesting stuff and log it.
// don't be a CPU hog
sleep(1);
}
?>
Embellishments: To make your script directly executable: chmod +x yourscript.php and add #!/usr/bin/php to the beginning of yourscript
修饰:使您的脚本直接可执行: chmod +x yourscript.php 并将 #!/usr/bin/php 添加到您的脚本的开头
To start with apache, you should add that command to your apache startup script (usually apachectl) and be sure to add code to kill it when apache stops.
要从 apache 开始,您应该将该命令添加到您的 apache 启动脚本(通常是 apachectl)中,并确保添加代码以在 apache 停止时终止它。
The check if you are already running involves a file with your PID in /var/locks/ and something like system('/bin/ps '.$thePID); It also makes the kill instruction easier to write.
检查您是否已经在运行涉及 /var/locks/ 中带有 PID 的文件以及类似 system('/bin/ps '.$thePID); 的文件。它还使 kill 指令更易于编写。
回答by Hassan Saeed
thanks Todd Chaffee but it is not working for me so i edited your code i hope you will not mind and may be it will also help others with this technique
感谢托德查菲,但它对我不起作用,所以我编辑了你的代码,希望你不会介意,也许它也会帮助其他人使用这种技术
cornjobpage.php //mainpage
cornjobpage.php //主页
<?php
//if you want to call page for multiples time w.r.t array
//then uncomment loop start & end)
?>
<?php
//foreach ($inputkeywordsArr as $singleKeyword) {
$url="http://localhost/projectname/testpage.php";
$params['Keywordname'] = "testValue";//$singleKeyword
post_async($url, $params);
//}//foreach ($inputkeywordsArr end
?>
<?php
/*
* Executes a PHP page asynchronously so the current page does not have to wait for it to finish running.
*
*/
function post_async($url, array $params)
{
foreach ($params as $key => &$val) {
if (is_array($val)) $val = implode(',', $val);
$post_params[] = $key.'='.urlencode($val);
}
$post_string = implode('&', $post_params);
$parts=parse_url($url);
$fp = fsockopen($parts['host'],
isset($parts['port'])?$parts['port']:80,
$errno, $errstr, 30);
$out = "GET ".$parts['path']."?$post_string"." HTTP/1.1\r\n";//you can use POST instead of GET if you like
$out.= "Host: ".$parts['host']."\r\n";
$out.= "Content-Type: application/x-www-form-urlencoded\r\n";
$out.= "Content-Length: ".strlen($post_string)."\r\n";
$out.= "Connection: Close\r\n\r\n";
fwrite($fp, $out);
fclose($fp);
}
?>
testpage.php
测试页
<?
echo $_REQUEST["Keywordname"];//Output > testValue
?>