For example, if you need to create a function to send mobile phone text messages in batches, if you use a for loop to do it, when the number of text messages is large, it will not only be time-consuming, but also have a very low success rate.
So I thought of using PHP and MySQL to implement a message queue and send text messages one by one.
First, create a data table sms, including the following fields:
id,
phone, //Mobile phone number
content //SMS content
Save the text messages and mobile phone numbers that need to be sent sms table.
The implemented code is as follows:
<?php
while(true){
$item = $db->getFirstRecord(); //获取数据表第一条记录
if(!$item){//如果队列中没有数据,则结束定时器
break;
}
$res = $sms->send($item['phone'],$item['content']); //发送短信
if($res){
$db->deleteFristRecord(); //删除发送成功的记录
echo $item['phone'].'发送成功';
}else{
echo $item['phone'].'发送失败,稍后继续尝试';
}
sleep(10); //每隔十秒循环一次
}
echo 'Sent completed! ';
?>
For example, there is a send button in the background. Clicking it triggers the execution of the above program. Assume that every 10 seconds a piece of data is fetched from the database to send a text message.
Problem: If I click the send button and then directly click on other pages to do other things, instead of clicking on the page and waiting until the sending is completed before leaving, the above program will continue to execute. Or if I go to other pages, the loop will jump out and the text message will not be sent.
淡淡烟草味2017-05-19 10:09:28
PHP is single-threaded, that is, as soon as you start execution, you must either wait for it to be fully executed, or interrupt it in advance, and you cannot perform two accesses at the same time. If you need to process asynchronously after clicking a button and jump directly to do other things, then you need the swoole service to handle the things you want to process asynchronously.
给我你的怀抱2017-05-19 10:09:28
In this case, just run it directly in the command line mode without putting it on the background web page. Then the top code that exits when there is no data is changed to sleep for a period of time.
世界只因有你2017-05-19 10:09:28
You can take a look at the PHP-Cli mode. There is a video on MOOC.com, MySQL simulates sending emails through a queue, and the effect is similar to the main question.
给我你的怀抱2017-05-19 10:09:28
I think the original poster’s php+mysql is correct, but cron job still needs to be used. The cron job is to set the script to be executed every XX seconds.
If you have to give up crontab. Then recommend the following code
ignore_user_abort() //关掉浏览器,php脚本可以继续执行
set_time_limit(0) // 一直执行下去
$item = $db->getFirstRecord(); //获取数据表第一条记录
if(!$item){//如果队列中没有数据,则结束定时器
break;
}
$res = $sms->send($item['phone'],$item['content']); //发送短信
if($res){
$db->deleteFristRecord(); //删除发送成功的记录
echo $item['phone'].'发送成功';
}else{
echo $item['phone'].'发送失败,稍后继续尝试';
}
sleep(10); //每隔十秒循环一次