search
HomeBackend DevelopmentPHP TutorialImplementing asynchronous calling of multi-threaded program code in PHP_PHP tutorial

This article introduces in detail the implementation of asynchronous calling multi-threading methods in PHP. Next, we will send a recommendation email to 1,000 users. The user enters or imports the email account and submits it to the server for execution.

For example, there is a scenario where a recommendation email is sent to 1,000 users. The user enters or imports the email account and submits it to the server for sending.

The code is as follows Copy code
 代码如下 复制代码

$sqlserver/42852.htm target=_blank >count=count($emailarr);

for($i=0;$i

{

  sendmail(.....);//发送邮件

}

?>

$sqlserver/42852.htm target=_blank >count=count($emailarr);

for($i=0 ;$i{

sendmail(....);//Send mail

}

? >

This code has a very poor user experience and cannot be used in practice. First, sending so many emails will cause the server to run overtime. In fact, it will take a long time for users to wait. It will make users doubt and lose confidence in system products. However, the user does not need to wait until all 1,000 emails have been sent before submitting the message successfully. We can directly prompt the user to send it successfully after submitting it to the background, and then let the background program silently send it one by one.


At this time we need "asynchronous execution" technology to execute the code. The characteristic of asynchronous execution is silent execution in the background. The user does not need to wait for the execution result of the code. The benefits of using asynchronous execution:

1 . Get rid of the application's dependence on a single task

2. Improve the execution efficiency of the program

 代码如下 复制代码

$domain="www.***.com";
$url="/system_mail.php";
$par="email=".implode(',',$emailarr)."&........";
$header = "POST $url HTTP/1.0rn";
$header .= "Content-Type: application/x-www-form-urlencodedrn";
$header .= "Content-Length: " . strlen($par) . "rnrn";
$fp = @fsockopen ($domain, 80, $errno, $errstr, 30);
fputs ($fp, $header . $par);
fclose($fp);

echo ''发送完毕';
?>
system_mail.php
ini_set("ignore_user_abort",true);
ignore_user_abort(true);//此处的代码需要php.ini开启相关的选项,保证php执行不超时的,不明白,参考我的另一篇文章 “关闭浏览器后,php脚本会不会继续运行”
//获取email地址,发信,此处为发信代码
?>

3. Improve the scalability of the program4. In certain scenarios Improved user experience5. Because PHP does not support multi-threading, using asynchronous calls to request multiple HTTPs achieves the effect of parallel execution of the program. However, please note that if too many HTTP requests are requested, the time will be greatly increased. The system overhead is increasedUser experience: User waits ->Sending completedFriends will ask, why is the sending link missing? OK, when the user submits the request, the email sending task is transferred to a PHP program that handles the sending of letters separately. When the user sees "Sent Complete", the letter has not been sent yet. At this time, the mail-sending program is working hard in the background, sending out letters one by one sendmail.php

Okay, after changing to asynchronous mode, the user can submit the information and get the result "sent completed" immediately. Letters will be sent one by one in the background until they are sent.


After testing, I have summarized several methods and share them with you:
1. The simplest way is to embed an AJAX call in the HTML code returned to the client, or embed an img tag, src points to the time-consuming script to be executed.
This method is the simplest and fastest. The server does not need to make any calls.
But the disadvantage is that generally speaking, Ajax should be triggered after onLoad. That is to say, if the user clicks on the page and then closes it, our background script will not be triggered.
If you use the img tag, this method cannot be called asynchronous execution in the strict sense. The user's browser will wait for a long time for the execution of the php script to be completed, that is, the status bar of the user's browser always shows that it is still loading.
Of course, other methods with similar principles can also be used, such as script tags, etc.

2. popen()

resource popen (string command, string mode);
//Open a pipe pointing to the process that is executed by deriving the given command command produce. Opens a pipe to the process spawned by execution of the command that spawned the given command.

So you can call it but ignore its output.

The code is as follows Copy code
$domain= "www.***.com";$url="/system_mail.php";$par="email=".implode(',',$emailarr)."&.... ....";$header = "POST $url HTTP/1.0rn";$header .= "Content-Type: application/x-www-form-urlencodedrn";$header .= "Content-Length: " . strlen($par) . "rnrn";$fp = @fsockopen ($domain, 80, $errno, $errstr, 30);fputs ($fp, $header . $par);fclose($fp);echo ''Sent completed';?>system_mail.phpini_set("ignore_user_abort",true);ignore_user_abort(true);//The code here requires php.ini to enable relevant options to ensure that PHP execution does not time out. If you don’t understand, please refer to my other article "Will the php script continue to run after closing the browser?" //Get the email address and send a message. Here is the sending code ?>
 代码如下 复制代码
pclose(popen("/home/xinchen/backend.php &", 'r'));

This method avoids the shortcomings of the first method and is also fast. But the problem is that this method cannot request another WebService through the HTTP protocol and can only execute local script files. And it can only be opened in one direction, and cannot pass a large number of parameters to the called script.
And if the number of visits is high, a large number of processes will be generated. If you use external resources, you have to consider the competition yourself.

3. Use the CURL
method and set CUROPT_TIMEOUT to 1 (the minimum is 1, depressing). That is, the client must wait at least 1 second.

$curl_opt = array(CURLOPT_URL, 'http://www.example.com/backend.php',
The code is as follows
 代码如下 复制代码

$ch = curl_init();

 $curl_opt = array(CURLOPT_URL, 'http://www.example.com/backend.php',

                            CURLOPT_RETURNTRANSFER, 1,

                            CURLOPT_TIMEOUT, 1,);

 

curl_setopt_array($ch, $curl_opt);

 

curl_exec($ch);

 

curl_close($ch);

Copy code


$ch = curl_init();
 代码如下 复制代码

$fp = fsockopen("www.example.com", 80, $errno, $errstr, 30);

if (!$fp) {

    echo "$errstr ($errno)
n";

} else {

    $out = "GET /backend.php / HTTP/1.1rn";

    $out .= "Host: www.example.comrn";

    $out .= "Connection: Closernrn";

 

    fwrite($fp, $out);

    /*忽略执行结果

while (!feof($fp)) {

echo fgets($fp, 128);

}*/

    fclose($fp);

}

CURLOPT_RETURNTRAN SFER , 1, CURLOPT_TIMEOUT, 1,); curl_setopt_array($ch, $curl_opt);curl_exec( $ch); curl_close($ch); 4. Using fsockopen should be the most perfect method Yes, but the disadvantage is that you need to spell out the HTTP header part yourself.
The code is as follows Copy code
$fp = fsockopen("www.example.com", 80, $errno, $errstr, 30);if (!$fp) { echo "$errstr ($errno)
n";} else { $out = "GET /backend.php / HTTP/1.1rn"; $out .= "Host: www.example.comrn"; $out .= "Connection: Closernrn"; fwrite($fp , $out); /*Ignore the execution resultwhile (!feof($fp)) {echo fgets($fp, 128); }*/ fclose($fp);}

www.bkjia.comtruehttp: //www.bkjia.com/PHPjc/444683.htmlTechArticleThis article introduces in detail the implementation of asynchronous calling multi-threading methods in PHP. Below we will send it to 1000 users A recommendation email, the user enters or imports the email account to submit the service...
Statement
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn
php怎么把负数转为正整数php怎么把负数转为正整数Apr 19, 2022 pm 08:59 PM

php把负数转为正整数的方法:1、使用abs()函数将负数转为正数,使用intval()函数对正数取整,转为正整数,语法“intval(abs($number))”;2、利用“~”位运算符将负数取反加一,语法“~$number + 1”。

php怎么实现几秒后执行一个函数php怎么实现几秒后执行一个函数Apr 24, 2022 pm 01:12 PM

实现方法:1、使用“sleep(延迟秒数)”语句,可延迟执行函数若干秒;2、使用“time_nanosleep(延迟秒数,延迟纳秒数)”语句,可延迟执行函数若干秒和纳秒;3、使用“time_sleep_until(time()+7)”语句。

php怎么除以100保留两位小数php怎么除以100保留两位小数Apr 22, 2022 pm 06:23 PM

php除以100保留两位小数的方法:1、利用“/”运算符进行除法运算,语法“数值 / 100”;2、使用“number_format(除法结果, 2)”或“sprintf("%.2f",除法结果)”语句进行四舍五入的处理值,并保留两位小数。

php怎么根据年月日判断是一年的第几天php怎么根据年月日判断是一年的第几天Apr 22, 2022 pm 05:02 PM

判断方法:1、使用“strtotime("年-月-日")”语句将给定的年月日转换为时间戳格式;2、用“date("z",时间戳)+1”语句计算指定时间戳是一年的第几天。date()返回的天数是从0开始计算的,因此真实天数需要在此基础上加1。

php字符串有没有下标php字符串有没有下标Apr 24, 2022 am 11:49 AM

php字符串有下标。在PHP中,下标不仅可以应用于数组和对象,还可应用于字符串,利用字符串的下标和中括号“[]”可以访问指定索引位置的字符,并对该字符进行读写,语法“字符串名[下标值]”;字符串的下标值(索引值)只能是整数类型,起始值为0。

php怎么替换nbsp空格符php怎么替换nbsp空格符Apr 24, 2022 pm 02:55 PM

方法:1、用“str_replace(" ","其他字符",$str)”语句,可将nbsp符替换为其他字符;2、用“preg_replace("/(\s|\&nbsp\;||\xc2\xa0)/","其他字符",$str)”语句。

php怎么判断有没有小数点php怎么判断有没有小数点Apr 20, 2022 pm 08:12 PM

php判断有没有小数点的方法:1、使用“strpos(数字字符串,'.')”语法,如果返回小数点在字符串中第一次出现的位置,则有小数点;2、使用“strrpos(数字字符串,'.')”语句,如果返回小数点在字符串中最后一次出现的位置,则有。

php怎么读取字符串后几个字符php怎么读取字符串后几个字符Apr 22, 2022 pm 08:31 PM

在php中,可以使用substr()函数来读取字符串后几个字符,只需要将该函数的第二个参数设置为负值,第三个参数省略即可;语法为“substr(字符串,-n)”,表示读取从字符串结尾处向前数第n个字符开始,直到字符串结尾的全部字符。

See all articles

Hot AI Tools

Undresser.AI Undress

Undresser.AI Undress

AI-powered app for creating realistic nude photos

AI Clothes Remover

AI Clothes Remover

Online AI tool for removing clothes from photos.

Undress AI Tool

Undress AI Tool

Undress images for free

Clothoff.io

Clothoff.io

AI clothes remover

AI Hentai Generator

AI Hentai Generator

Generate AI Hentai for free.

Hot Article

R.E.P.O. Energy Crystals Explained and What They Do (Yellow Crystal)
2 weeks agoBy尊渡假赌尊渡假赌尊渡假赌
Repo: How To Revive Teammates
1 months agoBy尊渡假赌尊渡假赌尊渡假赌
Hello Kitty Island Adventure: How To Get Giant Seeds
4 weeks agoBy尊渡假赌尊渡假赌尊渡假赌

Hot Tools

Safe Exam Browser

Safe Exam Browser

Safe Exam Browser is a secure browser environment for taking online exams securely. This software turns any computer into a secure workstation. It controls access to any utility and prevents students from using unauthorized resources.

SublimeText3 Linux new version

SublimeText3 Linux new version

SublimeText3 Linux latest version

SublimeText3 Chinese version

SublimeText3 Chinese version

Chinese version, very easy to use

Notepad++7.3.1

Notepad++7.3.1

Easy-to-use and free code editor

SublimeText3 Mac version

SublimeText3 Mac version

God-level code editing software (SublimeText3)