Usage scenarios
If you need to perform a time-consuming operation in the Server program, such as a chat server sending Broadcast, send emails from the web server. If you directly execute these functions, the current process will be blocked, causing the server to respond slowly. For example: In the user registration scenario, the function of completing registration and sending activation emails requires the following steps:
The client submits POST data -> The server obtains the data -> Completes the registration and writes the user data to the database - > Send account activation email-> Return to the client to prompt that the registration is successful.
There is no problem with this business logic, but sending an email is a time-consuming operation (such as 2-3s) and will synchronously block the execution of the program until the client is prompted to register successfully after the sending is successful. In this process, it is estimated that it takes about 4 seconds from submission to the final notification of successful registration. A request response takes 4 seconds, which is definitely unreasonable!
Now using Task asynchronous task delivery can greatly improve the user experience. The general process is:
The client submits POST data-> The server obtains the data-> Completes the registration and writes the user data to the database -> Immediately return to the client to prompt that the registration is successful.
Deliver a Task task when the registration is successful -> Complete the time-consuming operation of sending the email asynchronously (the user is unaware of this part of the time, because the response has been returned to the client very early).
How to use Think-Swoole's Task asynchronous task steps
Define event listening class (php think make:listener class name).
The event monitoring of swoole.task is defined in the app/event.php file.
Get the Swoole/Server object and call the task method (pass the listening class just defined in the parameter).
Define the trigger callback logic code in the handle method of the event listening class just defined.
Call the finish method that triggers task swoole.finish after the task is completed (called only when needed, not required).
Demo
First, create an email sending event in the project root directory:
php think make:listener EmailTask
Then define the created email sending event:
app/event.php 'listen' => [ 'AppInit' => [], 'HttpRun' => [], 'HttpEnd' => [], 'LogLevel' => [], 'LogWrite' => [], 'swoole.task' => [ app\listener\EmailTask::class, ], // 'swoole.finish' => [ // app\listener\EmailTaskFinish::class, // ], ],
The key name of swoole.task is Task. Tasks are written in a fixed way and cannot be named arbitrarily.
Next, we call the Task asynchronous task through the Swoole/Server class in the controller responsible for user registration. Of course, we must first improve the logic code of EmailTask.php:
app/ listener/EmailTask.php
<?php declare (strict_types = 1); namespace app\listener; class EmailTask { /** * 事件监听处理 * * @return mixed */ public function handle($event) { echo "开始发送邮件:".time(); //模拟耗时 3 秒,测试是否在响应事件内 sleep(3); echo "邮件发送成功:".time(); // 可以调用 finish 方法通知其他事件类,通知当前异步任务已经完成了(非必须调用) // 参数 $event 是 Swoole\Server\Task 类的一个对象 可以调用 finish 方法触发 task 任务的 onFinish 事件 // $event -> finish(\app\listener\EmailTaskFinish::class); } }
Registration method app/controller/Register.php
<?php namespace app\controller; use app\BaseController; class Register extends BaseController { public function register(\Swoole\Server $server) { if($this -> request -> isPost()){ $data = $this -> request -> post(); //TODO 调用验证类验证数据 //TODO 将注册信息插入数据库 // 这里调用 Task 异步任务 $server -> task(\app\listener\EmailTask::class); // 方式二 // $manager = app('\think\swoole\Manager'); // $manager -> getServer() -> task(\app\listener\EmailTask::class); return "注册成功!".time(); } } }
In the registration business, after inserting into the database, the asynchronous task of sending emails is called, and the email is simulated in EmailTask.php It takes 3 seconds.
Open the Think-Swoole service, access the registration method, and test whether the time for sending emails is included in the user registration method:
Visible, the email is sent The 3 seconds are performed asynchronously and the user is not aware of it.
In addition, there is a swoole.finish event, which is used to notify other events that the current asynchronous task has been completed. You also need to create an event and define swoole.finish in app/event.php. The above sample code has been demonstrated .
The above is the detailed content of Think-Swoole Task asynchronous task. For more information, please follow other related articles on the PHP Chinese website!

The article discusses ThinkPHP's built-in testing framework, highlighting its key features like unit and integration testing, and how it enhances application reliability through early bug detection and improved code quality.

Article discusses using ThinkPHP for real-time stock market data feeds, focusing on setup, data accuracy, optimization, and security measures.

The article discusses key considerations for using ThinkPHP in serverless architectures, focusing on performance optimization, stateless design, and security. It highlights benefits like cost efficiency and scalability, but also addresses challenges

The article discusses implementing service discovery and load balancing in ThinkPHP microservices, focusing on setup, best practices, integration methods, and recommended tools.[159 characters]

ThinkPHP's IoC container offers advanced features like lazy loading, contextual binding, and method injection for efficient dependency management in PHP apps.Character count: 159

The article discusses using ThinkPHP to build real-time collaboration tools, focusing on setup, WebSocket integration, and security best practices.

ThinkPHP benefits SaaS apps with its lightweight design, MVC architecture, and extensibility. It enhances scalability, speeds development, and improves security through various features.

The article outlines building a distributed task queue system using ThinkPHP and RabbitMQ, focusing on installation, configuration, task management, and scalability. Key issues include ensuring high availability, avoiding common pitfalls like imprope


Hot AI Tools

Undresser.AI Undress
AI-powered app for creating realistic nude photos

AI Clothes Remover
Online AI tool for removing clothes from photos.

Undress AI Tool
Undress images for free

Clothoff.io
AI clothes remover

AI Hentai Generator
Generate AI Hentai for free.

Hot Article

Hot Tools

PhpStorm Mac version
The latest (2018.2.1) professional PHP integrated development tool

MantisBT
Mantis is an easy-to-deploy web-based defect tracking tool designed to aid in product defect tracking. It requires PHP, MySQL and a web server. Check out our demo and hosting services.

WebStorm Mac version
Useful JavaScript development tools

Notepad++7.3.1
Easy-to-use and free code editor

MinGW - Minimalist GNU for Windows
This project is in the process of being migrated to osdn.net/projects/mingw, you can continue to follow us there. MinGW: A native Windows port of the GNU Compiler Collection (GCC), freely distributable import libraries and header files for building native Windows applications; includes extensions to the MSVC runtime to support C99 functionality. All MinGW software can run on 64-bit Windows platforms.