Backend Development
PHP Tutorial
How to trigger the background asynchronous batch sending of SMS messages in the foreground without affecting the user experience?
How to trigger the background asynchronous batch sending of SMS messages in the foreground without affecting the user experience?
This article introduces how to enable the front-end to trigger the background to send text messages in batches without affecting the user experience. After the user clicks the button, the front desk immediately returns the success prompt, and the back desk performs database query, Redis cache write and SMS sending asynchronously.

Core idea: asynchronous processing
This solution uses an asynchronous processing mechanism to move time-consuming operations to the background to perform, avoiding blocking the foreground. The specific steps are as follows:
-
Front-end Ajax request: The user clicks the send button, and the front-end uses Ajax to send a request to the background. The request parameters include the SMS template ID, mobile phone number list and SMS content.
$.ajax({ url: '/send-sms', type: 'POST', data: { template_id: 123, mobiles: ['13800138000', '13800138001'], content: 'Test SMS' }, success: function(response) { alert('SMS send request has been submitted'); }, error: function(error) { alert('Request failed:' error.responseText); } }); -
The background receives the request and returns the response: After the background receives the Ajax request, it immediately returns a successful response (JSON format) to inform the front-end that the request has been received. The key is that the SMS sending logic is put into an asynchronous task.
// Background controller method public function sendSmsAction() { $templateId = $_POST['template_id']; $mobiles = $_POST['mobiles']; $content = $_POST['content']; // Return the successful response immediately echo json_encode(['success' => true, 'message' => 'Request received, SMS sending task started']); // Add tasks to queues (for example using Redis or RabbitMQ) $this->addTaskToQueue($templateId, $mobiles, $content); } -
Asynchronous task processing:
addTaskToQueuemethod adds SMS sending task to the message queue. An independent background process (for example, using queue workers) continuously listens to the queue, fetches tasks and executes them.// Add tasks to queue (example using Redis) private function addTaskToQueue($templateId, $mobiles, $content) { $redis = new Redis(); $redis->connect('127.0.0.1', 6379); $redis->lPush('sms_queue', json_encode(['template_id' => $templateId, 'mobiles' => $mobiles, 'content' => $content])); } -
Queue Worker: Queue Worker obtains tasks from the
sms_queuequeue, performs SMS sending, and processes error logs.// Queue Worker (Example) while (true) { $task = $redis->rPop('sms_queue'); if ($task) { $data = json_decode($task, true); $result = $this->sendSms($data['template_id'], $data['mobiles'], $data['content']); if ($result !== true) { // Log error_log("SMS send failed: " . $result); } } sleep(1); // Avoid excessive CPU usage} SMS send function (
sendSms) : This function calls the SMS service provider API to send SMS messages.
Through the above steps, the front-end user experience will not be affected, and the back-end will efficiently process batch SMS sending. Choosing the right queue system (Redis, RabbitMQ, Beanstalkd, etc.) is crucial, which ensures that tasks are processed reliably and supports distributed environments. In addition, a complete error handling and logging mechanism is also essential.
The above is the detailed content of How to trigger the background asynchronous batch sending of SMS messages in the foreground without affecting the user experience?. For more information, please follow other related articles on the PHP Chinese website!
Hot AI Tools
Undress AI Tool
Undress images for free
Undresser.AI Undress
AI-powered app for creating realistic nude photos
AI Clothes Remover
Online AI tool for removing clothes from photos.
Clothoff.io
AI clothes remover
Video Face Swap
Swap faces in any video effortlessly with our completely free AI face swap tool!
Hot Article
Hot Tools
Notepad++7.3.1
Easy-to-use and free code editor
SublimeText3 Chinese version
Chinese version, very easy to use
Zend Studio 13.0.1
Powerful PHP integrated development environment
Dreamweaver CS6
Visual web development tools
SublimeText3 Mac version
God-level code editing software (SublimeText3)
Hot Topics
Java Chinese garbled problem, cause and fix for garbled code
May 28, 2025 pm 05:36 PM
The garbled problem in Java Chinese is mainly caused by inconsistent character encoding. The repair method includes ensuring the consistency of the system encoding and correctly handling encoding conversion. 1.Use UTF-8 encoding uniformly from files to databases and programs. 2. Clearly specify the encoding when reading the file, such as using BufferedReader and InputStreamReader. 3. Set the database character set, such as MySQL using the ALTERDATABASE statement. 4. Set Content-Type to text/html;charset=UTF-8 in HTTP requests and responses. 5. Pay attention to encoding consistency, conversion and debugging skills to ensure the correct processing of data.
How to limit user resources in Linux? How to configure ulimit?
May 29, 2025 pm 11:09 PM
Linux system restricts user resources through the ulimit command to prevent excessive use of resources. 1.ulimit is a built-in shell command that can limit the number of file descriptors (-n), memory size (-v), thread count (-u), etc., which are divided into soft limit (current effective value) and hard limit (maximum upper limit). 2. Use the ulimit command directly for temporary modification, such as ulimit-n2048, but it is only valid for the current session. 3. For permanent effect, you need to modify /etc/security/limits.conf and PAM configuration files, and add sessionrequiredpam_limits.so. 4. The systemd service needs to set Lim in the unit file
blockdag (bdag): The remaining 7 days, the remaining stack before going online
May 26, 2025 pm 11:51 PM
For good reason, Blockdag focuses on buyer interests. Blockdag has raised an astonishing $265 million in 28 batches of its pre-sales As 2025 approaches, investors are steadily accumulating high-potential crypto projects. Whether it’s low-cost pre-sale coins that offer a lot of upside, or a blue chip network that prepares for critical upgrades, this moment provides a unique entry point. From fast scalability to flexible modular blockchain architecture, these four outstanding names have attracted attention throughout the market. Analysts and early adopters are watching closely, calling them the best crypto coins to buy short-term gains and long-term value now. 1. BlockDag (BDAG): 7 days left
Performance Tuning of Jenkins Deployment on Debian
May 28, 2025 pm 04:51 PM
Deploying and tuning Jenkins on Debian is a process involving multiple steps, including installation, configuration, plug-in management, and performance optimization. Here is a detailed guide to help you achieve efficient Jenkins deployment. Installing Jenkins First, make sure your system has a Java environment installed. Jenkins requires a Java runtime environment (JRE) to run properly. sudoaptupdatesudoaptininstallopenjdk-11-jdk Verify that Java installation is successful: java-version Next, add J
What is Middleware in Laravel? How to use it?
May 29, 2025 pm 09:27 PM
Middleware is a filtering mechanism in Laravel that is used to intercept and process HTTP requests. Use steps: 1. Create middleware: Use the command "phpartisanmake:middlewareCheckRole". 2. Define processing logic: Write specific logic in the generated file. 3. Register middleware: Add middleware in Kernel.php. 4. Use middleware: Apply middleware in routing definition.
Laravel Page Cache Policy
May 29, 2025 pm 09:15 PM
Laravel's page caching strategy can significantly improve website performance. 1) Use cache helper functions to implement page caching, such as the Cache::remember method. 2) Select the appropriate cache backend, such as Redis. 3) Pay attention to data consistency issues, and you can use fine-grained caches or event listeners to clear the cache. 4) Further optimization is combined with routing cache, view cache and cache tags. By rationally applying these strategies, website performance can be effectively improved.
Free Korean comics online viewing free comics entrance Free Korean comics online reading free pull-down
Jun 12, 2025 pm 08:03 PM
With the vigorous development of the Internet, Korean comics (Korean comics) have won the love of more and more readers around the world with their exquisite painting style, fascinating plots and rich and diverse themes. If you want to travel anywhere, in the exciting Korean comic world, it is crucial to find a stable, free and resource-rich online reading platform. This article will provide you with a detailed guide to watching Korean comics online for free comics, helping you easily start your Korean comic journey.
Kakao-backed Kaia plans to launch Korean won anchor stablecoin
Jun 12, 2025 pm 12:51 PM
Kaia, a public chain platform invested by South Korean instant messaging giant Kakao, announced that it plans to launch a stablecoin pegged to the Korean won (KRW) on June 9. This move is seen as a strategic move to expand the digital financial ecosystem of South Korea's domestic market, and also responds to the cryptocurrency development direction proposed by South Korean President Lee Jae-ming during his campaign. The issuance of stablecoins pegged to the Korean won is expected to become an important bridge between the South Korean blockchain world and the traditional financial system. As the legal environment of the cryptocurrency industry gradually improves and clarifies, Kaia said it will focus on the domestic market and take advantage of its technological advantages to promote the widespread, safe, legal and compliant use of stablecoins. Stable coins pegged to Korean won


