本篇文章给大家带来的内容是关于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, ], 'App\Events\UserBrowse' => [ 'App\Listeners\CreateBrowseLog',// 用户访问记录 'App\Listeners\CreateUserIpLog',// 用户 IP 记录 ], ];
添加完成后执行 php artisan event:generate,创建好了 app/Listeners/CreateUserIpLog.php 文件;
/** * 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 记录下来,然后就是编写统计代码
/** * 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)); }
设置任务调度
/** * The Artisan commands provided by your application. * * @var array */ protected $commands = [ \App\Console\Commands\CountIpDay::class, ];
/** * Define the application's command schedule. * * @param \Illuminate\Console\Scheduling\Schedule $schedule * @return void */ protected function schedule(Schedule $schedule) { $schedule->command('countIp:day')->dailyAt('1:00'); }
以上就是laravel任务调度的介绍(附代码)的详细内容,更多请关注php中文网其它相关文章!
每个人都需要一台速度更快、更稳定的 PC。随着时间的推移,垃圾文件、旧注册表数据和不必要的后台进程会占用资源并降低性能。幸运的是,许多工具可以让 Windows 保持平稳运行。
Copyright 2014-2025 https://www.php.cn/ All Rights Reserved | php.cn | 湘ICP备2023035733号