laravel任務調度的介紹(附代碼)

本篇文章給大家帶來的內容是關于laravel任務調度的介紹(附代碼),有一定的參考價值,有需要的朋友可以參考一下,希望對你有所幫助。

導語:之前寫過使用 linux 的進行定時任務,實際上 laravel 也可以執行定時任務。需求是統計每日訪問的 IP 數,雖然數據表中有數據,為了演示,新建監聽器統計。

記錄 IP

這篇文章中介紹了實現了事件/監聽器,在此基礎上進行擴展。

注冊一個新的監聽器,在?app/Providers/EventServiceProvider.php?文件中新添加?CreateUserIpLog

/**      * The event listener mappings for the application.      *      * @var array      */     protected $listen = [         Registered::class => [             SendEmailVerificationNotification::class,         ],         'AppEventsUserBrowse' => [             'AppListenersCreateBrowseLog',// 用戶訪問記錄             'AppListenersCreateUserIpLog',// 用戶 IP 記錄         ],     ];

添加完成后執行 php artisan event:generate,創建好了 app/Listeners/CreateUserIpLog.php 文件;

  1. 在新建監聽器中,記錄用戶的 IP,使用 redis 的 Set 數據類型進行記錄,代碼如下
/**      * Handle the event.      * 記錄用戶 IP      * @param  UserBrowse $event      * @return void      */     public function handle(UserBrowse $event)     {         $redis = Redis::connection('cache');         $redisKey = 'user_ip:' . Carbon::today()->format('Y-m-d');          $isExists = $redis->exists($redisKey);          $redis->sadd($redisKey, $event->ip_addr);          if (!$isExists) {             // key 不存在,說明是當天第一次存儲,設置過期時間三天             $redis->expire($redisKey, 259200);         }     }

統計訪問

上面將用戶的 IP 記錄下來,然后就是編寫統計代碼

  1. 新建一個任務 php artisan make:command CountIpDay,新建了 app/console/Commands/CountIpDay.php 文件;
  2. 設置簽名 protected $signature = ‘countIp:day’; 和描述 protected $description = ‘統計每日訪問 IP’;
  3. 在 handle 方法中編寫代碼,也可以在 kernel.php 中使用 emailOutputTo 方法發送郵件
/**      * Execute the console command.      *      * @return mixed      */     public function handle()     {         $redis = Redis::connection('cache');         $yesterday = Carbon::yesterday()->format('Y-m-d');         $redisKey = 'user_ip:' . $yesterday;          $data = $yesterday . ' 訪問 IP 總數為 ' . $redis->scard($redisKey);          // 發送郵件         Mail::to(env('ADMIN_EMAIL'))->send(new SendSystemInfo($data));     }

設置任務調度

  1. 編輯 app/Console/Kernel.php 的 $commands
/**      * The Artisan commands provided by your application.      *      * @var array      */     protected $commands = [         AppConsoleCommandsCountIpDay::class,     ];
  1. 在 schedule 方法中設置定時任務,執行時間為每天凌晨一點
/**      * Define the application's command schedule.      *      * @param  IlluminateConsoleSchedulingSchedule $schedule      * @return void      */     protected function schedule(Schedule $schedule)     {         $schedule->command('countIp:day')->dailyAt('1:00');     }

最后是在 Linux 中添加定時任務,每分鐘執行一次 artisan schedule:run,如下
* * * * * /you_php ?you_path/artisan schedule:run >> /dev/NULL 2>&1

? 版權聲明
THE END
喜歡就支持一下吧
點贊15 分享