您好,欢迎访问一九零五行业门户网

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,        ],        'app\events\userbrowse' => [            'app\listeners\createbrowselog',// 用户访问记录            'app\listeners\createuseriplog',// 用户 ip 记录        ],    ];
添加完成后执行 php artisan event:generate,创建好了 app/listeners/createuseriplog.php 文件;
在新建监听器中,记录用户的 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 记录下来,然后就是编写统计代码
新建一个任务 php artisan make:command countipday,新建了 app/console/commands/countipday.php 文件;设置签名 protected $signature = 'countip:day'; 和描述 protected $description = '统计每日访问 ip';在 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));    }
设置任务调度
编辑 app/console/kernel.php 的 $commands/**     * the artisan commands provided by your application.     *     * @var array     */    protected $commands = [        \app\console\commands\countipday::class,    ];
在 schedule 方法中设置定时任务,执行时间为每天凌晨一点/**     * 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');    }
最后是在 linux 中添加定时任务,每分钟执行一次 artisan schedule:run,如下
* * * * * /you_php  you_path/artisan schedule:run >> /dev/null 2>&1
以上就是laravel任务调度的介绍(附代码)的详细内容。
其它类似信息

推荐信息