Implement Asynchronous calling of multi-thread program code in PHP

Source: Internet
Author: User

This article introduces in detail how to Implement Asynchronous calling of multi-threaded methods in PHP. Below we will send a recommendation email to 1000 users, the user entered or imported the email account and submitted it to the server for sending.

For example, in the current scenario, a recommendation email is sent to 1000 users. The user enters or imports the email account and submits it to the server for sending.

The Code is as follows: Copy code

<? Php

$ Sqlserver/42852.htm target = _ blank> count = count ($ emailarr );

For ($ I = 0; $ I <$ count; $ I)

{

Sendmail (...); // send an email

}

?>

The user experience of this code is very poor and cannot be used in practice. First, sending so many emails will result in server operation timeout. In fact, a long waiting time will cause the user to doubt and lose confidence in the system products. However, you do not need to wait until all the 1000 emails are sent before submitting the email successfully. You can submit the email to the backend and then send the message to the user.

At this time, we need the "Asynchronous execution" technology to execute code. asynchronous execution is characterized by silent execution in the background, and users do not have to wait for the code execution results. The advantages of asynchronous execution are as follows:

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

2. Improved program execution efficiency

3. Improved Program scalability

4. Improved user experience in certain scenarios

5. because PHP does not support multithreading, the asynchronous call of multiple HTTP requests achieves parallel execution of the program. However, if there are too many HTTP requests, the system overhead will be greatly increased.


User Experience: User waiting-> sending completed
Friends will ask, why is there a lack of email sending?
OK. When the user submits a request, the mail sending task is transferred to a php program that handles the mail separately, when the user sees that "sending is complete", the real message has not been sent. At this time, the sender program is working hard in the background and sending one letter to the outside.

Sendmail. php

The Code is as follows: Copy code

<? Php
$ 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 ''sending completed ';
?>
System_mail.php
<? Php
Ini_set ("ignore_user_abort", true );
Ignore_user_abort (true); // The code here requires php. enable related options in ini to ensure that php Execution does not time out. If you do not understand, refer to my other article "Will the php script continue to run after the browser is closed"
// Obtain the email address and send the email. The mail code is used here.
?>

After changing to the asynchronous mode, the user submits the information and can immediately get the result "sent ". The email is sent in the background until it is sent.


After testing, we have summarized several methods to share with you:
1. The simplest method 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.
However, the disadvantage is that Ajax should be triggered after onLoad. That is to say, when the user clicks the page and closes it, the background script will not be triggered.
Using the img label cannot be called a strictly asynchronous execution. The user's browser will wait for a long time until the php script is executed, that is, the status bar of the user's browser is still being loaded.
Of course, you can also use other similar methods, such as script labels.

2. popen ()

Resource popen (string command, string mode );
// Open an pipeline pointing to a process. This process is generated by the execution of the derived command. Open an pipeline pointing to a process, which is generated by running the command derived from a process.

Therefore, you can call it, but ignore its output.

The Code is as follows: Copy code
Pclose (popen ("/home/xinchen/backend. php &", 'R '));

This method avoids the disadvantages of the first method and is also very fast. However, the problem is that this method cannot request another WebService through the HTTP protocol and can only execute local script files. In addition, it can only be opened in one way, and a large number of parameters cannot be used to call scripts.
In addition, if the traffic is high, a large number of processes will be generated. If external resources are used, you must consider competition on your own.

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

The Code is as follows: Copy code

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

4. Use fsockopen
This method should be perfect, but the disadvantage is that you need to spell out the HTTP header.

The Code is as follows: Copy code

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

If (! $ Fp ){

Echo "$ errstr ($ errno) <br/> n ";

} Else {

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

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

$ Out. = "Connection: Closernrn ";

 

Fwrite ($ fp, $ out );

/* Ignore execution results

While (! Feof ($ fp )){

Echo fgets ($ fp, 128 );

}*/

Fclose ($ fp );

}


Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.