Home  >  Article  >  PHP Framework  >  Analysis of Laravel5.5 event monitoring, task scheduling, and queue

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

藏色散人
藏色散人forward
2021-06-19 16:03:102284browse

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
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));
    }

1.2 Create listener1.2.1 Method 1: Manually create

php artisan make:listener EmailAdminUserLogin --event=UserLogin

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) {
            //
        });
    }
}

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();
    }

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;);
    }
}
Kernel.php

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

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

3.2 Create task

Generate task class:

php artisan make:job SendReminderEmail
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);
    }
}

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';
    }
Route::get('/job', 'UserController@store');

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

Generate 5 queue tasks:

##3.4 Run queue processor

php artisan queue:work

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
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:
This article is reproduced at:segmentfault.com. If there is any infringement, please contact admin@php.cn delete