Table of Contents
1.2.2 Method 2:
Automatically generate events and listeners
Generate events & listeners:
auxiliary function. The only parameter that needs to be passed to
queue:work
Home PHP Framework Laravel Analysis of Laravel5.5 event monitoring, task scheduling, and queue

Analysis of Laravel5.5 event monitoring, task scheduling, and queue

Jun 19, 2021 pm 04:03 PM
laravel event listening

The following tutorial column will introduce you to the event monitoring, task scheduling, and queue of Laravel5.5. I hope it will be helpful to friends in need! Laravel5.5 event monitoring, task scheduling, queue

1. Event monitoring

Process:

1.1 Create event

php artisan make:event UserLogin
Copy after login
Analysis of Laravel5.5 event monitoring, task scheduling, and queueLoginController.php

    /**
     * The user has been authenticated.
     *
     * @param  \Illuminate\Http\Request  $request
     * @param  mixed  $user
     * @return mixed
     */
    protected function authenticated(Request $request, $user)
    {
        event(new UserLogin($user));
    }
Copy after login

1.2 Create listener1.2.1 Method 1: Manually create

php artisan make:listener EmailAdminUserLogin --event=UserLogin
Copy after login

1.2.2 Method 2:

Recommend the following method:

Automatically generate events and listeners

//应用程序的事件监听器映射

class EventServiceProvider extends ServiceProvider
{
    /**
     * The event listener mappings for the application.
     *
     * @var array
     */
    protected $listen = [
        'App\Events\UserLogin' => [
            'App\Listeners\UserLogin\EmailAdminUserLogin',
            'App\Listeners\UserLogin\TraceUser',
            'App\Listeners\UserLogin\AddUserLoginCounter',
        ],
        'App\Events\UserLogout' => [
            'App\Listeners\UserLogout\EmailAdminUserLogout',
            'App\Listeners\UserLogout\TraceUser',
        ],
    ];

    /**
     * Register any events for your application.
     *
     * @return void
     */
    public function boot()
    {
        parent::boot();

        Event::listen('event.*', function ($eventName, array $data) {
            //
        });
    }
}
Copy after login

Generate events & listeners:

php artisan event:generate

2. Laravel’s task scheduling (planned task) function Task Scheduling2.1 call method

protected function schedule(Schedule $schedule)
    {
        $schedule->call(function (){
            \Log::info('我是call方法实现的定时任务');
        })->everyMinute();
    }
Copy after login

Execution:

php artisan schedule:run

2.2 crontab method

2.2 command method

Analysis of Laravel5.5 event monitoring, task scheduling, and queue

Generate command:

php artisan make:command SayHello

<?php namespace App\Console\Commands;

use Illuminate\Console\Command;

class SayHello extends Command
{
    /**
     * The name and signature of the console command.
     *
     * @var string
     */
    protected $signature = &#39;message:hi&#39;;

    /**
     * The console command description.
     *
     * @var string
     */
    protected $description = &#39;Command description&#39;;

    /**
     * Create a new command instance.
     *
     * @return void
     */
    public function __construct()
    {
        parent::__construct();
    }

    /**
     * Execute the console command.
     *
     * @return mixed
     */
    public function handle()
    {
        //书写处理逻辑
        \Log::info(&#39;早上好,用户&#39;);
    }
}
Copy after login
Kernel.php

protected function schedule(Schedule $schedule)
{
    $schedule->command('message:hi')
             ->everyMinute();
}
Copy after login

Execution:

php artisan schedule:run

3. Queue tasks3.1 Necessary driver settings

QUEUE_DRIVER=database

For example: database driver

php artisan queue:table

php artisan migrate
Copy after login

3.2 Create task

Generate task class:

php artisan make:job SendReminderEmail
Copy after login
class SendReminderEmail implements ShouldQueue
{
    use Dispatchable, InteractsWithQueue, Queueable, SerializesModels;
    public $user;

    /**
     * Create a new job instance.
     *
     * @param User $user
     */
    public function __construct(User $user)
    {
        $this->user = $user;
    }

    /**
     * Execute the job.
     *
     * @return void
     */
    public function handle()
    {
        \Log::info('send reminder email to user' . $this->user->email);
    }
}
Copy after login

3.3 Distribute task After you write the task class, you can distribute it through the

dispatch

auxiliary function. The only parameter that needs to be passed to

dispatch

is an instance of this task class: Use the model factory to generate 30 users:

    public function store(Request $request)
    {
        $users = User::where('id','>',24)->get();

        foreach ($users as $user){
            $this->dispatch(new SendReminderEmail($user));
        }

        return 'Done';
    }
Copy after login
Route::get('/job', 'UserController@store');
Copy after login

Database tableAnalysis of Laravel5.5 event monitoring, task scheduling, and queuejobs

Generate 5 queue tasks:

##3.4 Run queue processor

php artisan queue:work
Copy after login

Analysis of Laravel5.5 event monitoring, task scheduling, and queueTips:

Be aware that once the

queue:work

command starts, it will run until you manually stop it or you close the console

Processing a single Task: You can use the --once

option to specify that only a single task in the queue will be processed

php artisan queue:work --once
Copy after login
Extension:

Use Analysis of Laravel5.5 event monitoring, task scheduling, and queueBeanstalkd

to manage the queue,

Supervisor is used to monitor the tasks in the queue, and automatically help us execute them if there are tasks in the queue, eliminating the need to manually type php artisan command to ensure that your queue can be executed correctly《Related recommendations: The latest five Laravel video tutorials

The above is the detailed content of Analysis of Laravel5.5 event monitoring, task scheduling, and queue. For more information, please follow other related articles on the PHP Chinese website!

Statement of this Website
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn

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

Video Face Swap

Video Face Swap

Swap faces in any video effortlessly with our completely free AI face swap tool!

Hot Tools

Notepad++7.3.1

Notepad++7.3.1

Easy-to-use and free code editor

SublimeText3 Chinese version

SublimeText3 Chinese version

Chinese version, very easy to use

Zend Studio 13.0.1

Zend Studio 13.0.1

Powerful PHP integrated development environment

Dreamweaver CS6

Dreamweaver CS6

Visual web development tools

SublimeText3 Mac version

SublimeText3 Mac version

God-level code editing software (SublimeText3)

How to get the return code when email sending fails in Laravel? How to get the return code when email sending fails in Laravel? Apr 01, 2025 pm 02:45 PM

Method for obtaining the return code when Laravel email sending fails. When using Laravel to develop applications, you often encounter situations where you need to send verification codes. And in reality...

How to implement the custom table function of clicking to add data in dcat admin? How to implement the custom table function of clicking to add data in dcat admin? Apr 01, 2025 am 07:09 AM

How to implement the table function of custom click to add data in dcatadmin (laravel-admin) When using dcat...

Laravel Redis connection sharing: Why does the select method affect other connections? Laravel Redis connection sharing: Why does the select method affect other connections? Apr 01, 2025 am 07:45 AM

The impact of sharing of Redis connections in Laravel framework and select methods When using Laravel framework and Redis, developers may encounter a problem: through configuration...

Laravel multi-tenant extension stancl/tenancy: How to customize the host address of a tenant database connection? Laravel multi-tenant extension stancl/tenancy: How to customize the host address of a tenant database connection? Apr 01, 2025 am 09:09 AM

Custom tenant database connection in Laravel multi-tenant extension package stancl/tenancy When building multi-tenant applications using Laravel multi-tenant extension package stancl/tenancy,...

Laravel Eloquent ORM in Bangla partial model search) Laravel Eloquent ORM in Bangla partial model search) Apr 08, 2025 pm 02:06 PM

LaravelEloquent Model Retrieval: Easily obtaining database data EloquentORM provides a concise and easy-to-understand way to operate the database. This article will introduce various Eloquent model search techniques in detail to help you obtain data from the database efficiently. 1. Get all records. Use the all() method to get all records in the database table: useApp\Models\Post;$posts=Post::all(); This will return a collection. You can access data using foreach loop or other collection methods: foreach($postsas$post){echo$post->

How to effectively check the validity of Redis connections in Laravel6 project? How to effectively check the validity of Redis connections in Laravel6 project? Apr 01, 2025 pm 02:00 PM

How to check the validity of Redis connections in Laravel6 projects is a common problem, especially when projects rely on Redis for business processing. The following is...

Laravel database migration encounters duplicate class definition: How to resolve duplicate generation of migration files and class name conflicts? Laravel database migration encounters duplicate class definition: How to resolve duplicate generation of migration files and class name conflicts? Apr 01, 2025 pm 12:21 PM

A problem of duplicate class definition during Laravel database migration occurs. When using the Laravel framework for database migration, developers may encounter "classes have been used...

Laravel Introduction Example Laravel Introduction Example Apr 18, 2025 pm 12:45 PM

Laravel is a PHP framework for easy building of web applications. It provides a range of powerful features including: Installation: Install the Laravel CLI globally with Composer and create applications in the project directory. Routing: Define the relationship between the URL and the handler in routes/web.php. View: Create a view in resources/views to render the application's interface. Database Integration: Provides out-of-the-box integration with databases such as MySQL and uses migration to create and modify tables. Model and Controller: The model represents the database entity and the controller processes HTTP requests.

See all articles