search
HomePHP FrameworkThinkPHPThink-Swoole Task asynchronous task

Think-Swoole Task asynchronous task

Oct 27, 2020 pm 01:39 PM
think-swoole

Think-Swoole Task asynchronous task

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(&#39;\think\swoole\Manager&#39;);
//            $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:

Think-Swoole Task asynchronous task

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!

Statement
This article is reproduced at:阿dai哥. If there is any infringement, please contact admin@php.cn delete
What Are the Key Features of ThinkPHP's Built-in Testing Framework?What Are the Key Features of ThinkPHP's Built-in Testing Framework?Mar 18, 2025 pm 05:01 PM

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.

How to Use ThinkPHP for Building Real-Time Stock Market Data Feeds?How to Use ThinkPHP for Building Real-Time Stock Market Data Feeds?Mar 18, 2025 pm 04:57 PM

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

What Are the Key Considerations for Using ThinkPHP in a Serverless Architecture?What Are the Key Considerations for Using ThinkPHP in a Serverless Architecture?Mar 18, 2025 pm 04:54 PM

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

How to Implement Service Discovery and Load Balancing in ThinkPHP Microservices?How to Implement Service Discovery and Load Balancing in ThinkPHP Microservices?Mar 18, 2025 pm 04:51 PM

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

What Are the Advanced Features of ThinkPHP's Dependency Injection Container?What Are the Advanced Features of ThinkPHP's Dependency Injection Container?Mar 18, 2025 pm 04:50 PM

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

How to Use ThinkPHP for Building Real-Time Collaboration Tools?How to Use ThinkPHP for Building Real-Time Collaboration Tools?Mar 18, 2025 pm 04:49 PM

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

What Are the Key Benefits of Using ThinkPHP for Building SaaS Applications?What Are the Key Benefits of Using ThinkPHP for Building SaaS Applications?Mar 18, 2025 pm 04:46 PM

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

How to Build a Distributed Task Queue System with ThinkPHP and RabbitMQ?How to Build a Distributed Task Queue System with ThinkPHP and RabbitMQ?Mar 18, 2025 pm 04:45 PM

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

See all articles

Hot AI Tools

Undresser.AI Undress

Undresser.AI Undress

AI-powered app for creating realistic nude photos

AI Clothes Remover

AI Clothes Remover

Online AI tool for removing clothes from photos.

Undress AI Tool

Undress AI Tool

Undress images for free

Clothoff.io

Clothoff.io

AI clothes remover

AI Hentai Generator

AI Hentai Generator

Generate AI Hentai for free.

Hot Article

R.E.P.O. Energy Crystals Explained and What They Do (Yellow Crystal)
3 weeks agoBy尊渡假赌尊渡假赌尊渡假赌
R.E.P.O. Best Graphic Settings
3 weeks agoBy尊渡假赌尊渡假赌尊渡假赌
R.E.P.O. How to Fix Audio if You Can't Hear Anyone
3 weeks agoBy尊渡假赌尊渡假赌尊渡假赌
WWE 2K25: How To Unlock Everything In MyRise
4 weeks agoBy尊渡假赌尊渡假赌尊渡假赌

Hot Tools

PhpStorm Mac version

PhpStorm Mac version

The latest (2018.2.1) professional PHP integrated development tool

MantisBT

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

WebStorm Mac version

Useful JavaScript development tools

Notepad++7.3.1

Notepad++7.3.1

Easy-to-use and free code editor

MinGW - Minimalist GNU for Windows

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.