Joke Collection Website - Public benefit messages - PHP+MYSQL realizes how to send short messages in queue.

PHP+MYSQL realizes how to send short messages in queue.

Recently, I met the demand of sending short messages in batches, and the short message interface was provided by a third party. At the beginning, I thought, after getting the mobile phone number, can't I call the interface to send it circularly?

But soon found the problem: when the number of short messages is large, it is not only time-consuming, but also the success rate is very low.

So I thought of using PHP and MySQL to realize a message queue and send text messages one by one. The following is the specific implementation method:

First, establish an sms data table, which contains the following fields:

id,

Phone,//phone number

Content//SMS content

Store the short messages and mobile phone numbers that need to be sent in the short message table.

Next, you need to implement a timer in PHP to periodically read records and send a short message:

& lt? Server-side programming language (abbreviation of professional hypertext preprocessor)

$ Db = new Db();

$ Sms = new Sms();

while(true){

$ item = $ d B- & gt; get first record(); //Get the first record in the data table

If (! $item){

//If there is no data in the queue, end the timer.

Break;

}

$ RES = $ SMS-& gt; Send($item[' phone'], $item[' content']); //Send SMS

if($res){

$ d B- & gt; deleteFristRecord(); //Delete the record of successful sending.

Echo $item['phone']。 "Sending succeeded";

} Otherwise {

Echo $item['phone']。 Sending failed, please try again later';

}

Sleep (10); //Cycle once every ten seconds.

}

Echo "Send complete!" ;

& gt

Save the code as timer_sms.php, open the command line and execute the timer:

Php timer _sms.php

Ok, the php timer will automatically complete the task of sending short messages according to the set time interval (here, 10 second). After the task is completed, it will automatically exit the timer and no longer occupy the server resources.

According to my test, PHP timer does not occupy too many resources and will not put pressure on the server. Moreover, accessing the database is asynchronous and will not affect the operation of the database.

The advantages of this method are:

1, running in the background, without waiting at the front desk.

2. The success rate is high, and the failed records will be automatically retransmitted until they are successful.