搜索
首页php框架Laravel解析Laravel5.5之事件监听、任务调度、队列

下面由laravel教程栏目给大家介绍Laravel5.5之事件监听、任务调度、队列,希望对需要的朋友有所帮助!

Laravel5.5之事件监听、任务调度、队列

一、事件监听

流程:

4141bcef64d4082ec180485995e0945.png

1.1 创建event

php artisan make:event UserLogin

LoginController.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 创建listener

1.2.1 方式一:手动创建

php artisan make:listener EmailAdminUserLogin --event=UserLogin

1.2.2 方式二:推荐如下方式:自动生成事件和监听

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

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

生成事件 & 监听器:php artisan event:generate

二、Laravel 的任务调度(计划任务)功能 Task Scheduling

2.1 call方式

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

执行:php artisan schedule:run

2.2 crontab方式

ec30296e321315018d2f94a3ae33b63.png

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

执行:php artisan schedule:run

三、队列任务

3.1 驱动的必要设置

    QUEUE_DRIVER=database

如:数据库驱动

php artisan queue:table

php artisan migrate

3.2 创建任务

     生成任务类:

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 分发任务

    你写好任务类后,就能通过 dispatch 辅助函数来分发它了。唯一需要传递给 dispatch 的参数是这个任务类的实例:
利用模型工厂生成30个用户:

6edf3c3bbe5853de183197f9060088d.png

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

数据库表jobs生成5个队列任务:

c7d38a7878f8e3989002265ee886da0.png

3.4 运行队列处理器

php artisan queue:work

Tips:要注意,一旦 queue:work 命令开始,它将一直运行,直到你手动停止或者你关闭控制台

处理单一任务:你可以使用 --once 选项来指定仅对队列中的单一任务进行处理

php artisan queue:work --once

624bc834907fb31be40228e8f0752b9.png

拓展:使用 Beanstalkd 管理队列,Supervisor 则是用来监听队列的任务,并在队列存在任务的情况下自动帮我们去执行,免去手动敲 php artisan 的命令,保证自己的队列可以正确执行

《相关推荐:最新的五个Laravel视频教程

以上是解析Laravel5.5之事件监听、任务调度、队列的详细内容。更多信息请关注PHP中文网其他相关文章!

声明
本文转载于:segmentfault。如有侵权,请联系admin@php.cn删除
包容的幻想:解决偏远工作中的孤立和孤独感包容的幻想:解决偏远工作中的孤立和孤独感Apr 25, 2025 am 12:28 AM

Tocombatisolationandlonelinessinremotework,companiesshouldimplementregular,meaningfulinteractions,provideequalgrowthopportunities,andusetechnologyeffectively.1)Fostergenuineconnectionsthroughvirtualcoffeebreaksandpersonalsharing.2)Ensureremoteworkers

Laravel用于全堆栈开发:综合指南Laravel用于全堆栈开发:综合指南Apr 25, 2025 am 12:27 AM

laravelispularfullull-stackDevelopmentBecapeitOffersAsAseAseAseAseBlendOfbackendEdpoperandPowerandForterFlexibility.1)ITSbackEndCapaPabilities,sightifyDatabaseInteractions.2)thebladeTemplatingEngingEngineAllolowsLows

视频会议摊牌:为远程会议选择正确的平台视频会议摊牌:为远程会议选择正确的平台Apr 25, 2025 am 12:26 AM

选择视频会议平台的关键因素包括用户界面、安全性和功能。1)用户界面应直观,如Zoom。2)安全性需重视,MicrosoftTeams提供端到端加密。3)功能需匹配需求,GoogleMeet适合简短会议,CiscoWebex提供高级协作工具。

哪些数据库版本与最新的Laravel兼容?哪些数据库版本与最新的Laravel兼容?Apr 25, 2025 am 12:25 AM

最新版本的Laravel10与MySQL5.7及以上、PostgreSQL9.6及以上、SQLite3.8.8及以上、SQLServer2017及以上兼容。这些版本选择是因为它们支持Laravel的ORM功能,如MySQL5.7的JSON数据类型,提升了查询和存储效率。

将Laravel用作全栈框架的好处将Laravel用作全栈框架的好处Apr 25, 2025 am 12:24 AM

laravelisanexceltentchoiceforfull-stackdevelopmentduetoitsRobustFeaturesAndEsofuse.1)ITSImplifiesComplexComplextaskSwithitSmodernphpsyNtaxandToolSandToolSlikeBlikeforFront-Endandeloquentormquentormquentormforback-end.2)

Laravel的最新版本是什么?Laravel的最新版本是什么?Apr 24, 2025 pm 05:17 PM

Laravel10,releasedonFebruary7,2023,isthelatestversion.Itfeatures:1)Improvederrorhandlingwithanewreportmethodintheexceptionhandler,2)EnhancedsupportforPHP8.1featureslikeenums,and3)AnewLaravel\Promptspackageforinteractivecommand-lineprompts.

最新的Laravel版本如何简化开发?最新的Laravel版本如何简化开发?Apr 24, 2025 pm 05:01 PM

thelatestlaravelververversionenhancesdevelopmentwith:1)简化的inimpliticmodelbinding,2)增强EnhancedeloquentcapabibilitionswithNewqueryMethods和3)改善了supportorfortormodernphpfortornphpforternphpfeatureserslikenamedargenamedArgonedArgonsemandArgoctess,makecodingMoreftermeforefterMealiteFficeAndEnjoyaigaigaigaigaigaiganigaborabilyaboipaigyAndenjoyaigobyabory。

在哪里可以找到最新的Laravel版本的发行说明?在哪里可以找到最新的Laravel版本的发行说明?Apr 24, 2025 pm 04:53 PM

你可以在laravel.com/docs找到最新Laravel版本的发布说明。1)发布说明提供了新功能、错误修复和改进的详细信息。2)它们包含示例和解释,帮助理解新功能的应用。3)注意新功能的潜在复杂性和向后兼容性问题。4)定期审查发布说明可以保持更新并激发创新。

See all articles

热AI工具

Undresser.AI Undress

Undresser.AI Undress

人工智能驱动的应用程序,用于创建逼真的裸体照片

AI Clothes Remover

AI Clothes Remover

用于从照片中去除衣服的在线人工智能工具。

Undress AI Tool

Undress AI Tool

免费脱衣服图片

Clothoff.io

Clothoff.io

AI脱衣机

Video Face Swap

Video Face Swap

使用我们完全免费的人工智能换脸工具轻松在任何视频中换脸!

热工具

Dreamweaver Mac版

Dreamweaver Mac版

视觉化网页开发工具

VSCode Windows 64位 下载

VSCode Windows 64位 下载

微软推出的免费、功能强大的一款IDE编辑器

SublimeText3 Mac版

SublimeText3 Mac版

神级代码编辑软件(SublimeText3)

安全考试浏览器

安全考试浏览器

Safe Exam Browser是一个安全的浏览器环境,用于安全地进行在线考试。该软件将任何计算机变成一个安全的工作站。它控制对任何实用工具的访问,并防止学生使用未经授权的资源。

Dreamweaver CS6

Dreamweaver CS6

视觉化网页开发工具