下面由laravel教程栏目给大家介绍laravel5.5之事件监听、任务调度、队列,希望对需要的朋友有所帮助!
Laravel5.5之事件监听、任务调度、队列
php artisan make:event UserLogin
/** * The user has been authenticated. * * @param IlluminateHttpRequest $request * @param mixed $user * @return mixed */ protected function authenticated(Request $request, $user) { event(new UserLogin($user)); }
php artisan make:listener EmailAdminUserLogin --event=UserLogin
//应用程序的事件监听器映射 class EventServiceProvider extends ServiceProvider { /** * The event listener mappings for the application. * * @var array */ protected $listen = [ 'AppEventsUserLogin' => [ 'AppListenersUserLoginEmailAdminUserLogin', 'AppListenersUserLoginTraceUser', 'AppListenersUserLoginAddUserLoginCounter', ], 'AppEventsUserLogout' => [ 'AppListenersUserLogoutEmailAdminUserLogout', 'AppListenersUserLogoutTraceUser', ], ]; /** * Register any events for your application. * * @return void */ public function boot() { parent::boot(); Event::listen('event.*', function ($eventName, array $data) { // }); } }
protected function schedule(Schedule $schedule) { $schedule->call(function (){ Log::info('我是call方法实现的定时任务'); })->everyMinute(); }
<?php namespace AppConsoleCommands; use IlluminateConsoleCommand; class SayHello extends Command { /** * The name and signature of the console command. * * @var string */ protected $signature = 'message:hi'; /** * The console command description. * * @var string */ protected $description = 'Command description'; /** * Create a new command instance. * * @return void */ public function __construct() { parent::__construct(); } /** * Execute the console command. * * @return mixed */ public function handle() { //书写处理逻辑 Log::info('早上好,用户'); } }
protected function schedule(Schedule $schedule) { $schedule->command('message:hi') ->everyMinute(); }
php artisan queue:table php artisan migrate
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); } }
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');
php artisan queue:work
php artisan queue:work --once
© 版权声明
文章版权归作者所有,未经允许请勿转载。
THE END