您现在的位置是: 网站首页> PHP> Laravel Laravel

Laravel任务调度实现定时任务

Smile 2019-08-23 PHP Laravel 阅读:907

简介用Laravel框架搭建了一个文章博客,需要每天零点清除旧的文章静态页缓存,生成新的静态页缓存,这样就不用人工手动去操作,节省了大量时间且省事,下面简单介绍下如何利用Laravel的任务调度实现这个定时任务需求

1、创建执行任务的脚本文件,当然你要是有多个任务,可以创建多个

php artisan make:command CreateHtml

2、打开脚本文件app\Console\Commands\CreateHtml.php

<?php

namespace App\Console\Commands;

use Illuminate\Console\Command;
use App\Http\Controllers\Admin\Article;

class CreateHtml extends Command
{
    /**
     * The name and signature of the console command.
     *
     * @var string
     */
    protected $signature = 'create:html';//执行脚本的命令

    /**
     * The console command description.
     *
     * @var string
     */
    protected $description = '创建文章静态页';//脚本描述

    /**
     * Create a new command instance.
     *
     * @return void
     */
    public function __construct()
    {
        parent::__construct();
    }

    /**
     * Execute the console command.
     *
     * @return mixed
     */
    public function handle()
    {
        //这里写生成静态页的脚本逻辑
        $obj = new Article();
        $obj->CreateHtml();
    }
}

3、打开app\Console\Kernel.php 文件,注册脚本

<?php

namespace App\Console;

use Illuminate\Console\Scheduling\Schedule;
use Illuminate\Foundation\Console\Kernel as ConsoleKernel;

class Kernel extends ConsoleKernel
{
    /**
     * The Artisan commands provided by your application.
     *
     * @var array
     */
    protected $commands = [
        //在这里注册脚本
        \App\Console\Commands\CreateHtml::class,
    ];

    /**
     * Define the application's command schedule.
     *
     * @param  \Illuminate\Console\Scheduling\Schedule  $schedule
     * @return void
     */
    protected function schedule(Schedule $schedule)
    {
        //这里定义任务调度
        $schedule->command('create:html')//CreateHtml.php中的signature
                 ->daily();//daily表示每天零时执行一次任务
    }

    /**
     * Register the commands for the application.
     *
     * @return void
     */
    protected function commands()
    {
        $this->load(__DIR__.'/Commands');

        require base_path('routes/console.php');
    }
}

4、执行脚本

php artisan schedule:run  //运行定时任务,启动调度器

5、立即执行一次脚本

php artisan create:html

6、接下来还要在Linux 中添加定时任务,每分钟执行一次  artisan schedule:run,如下

* * * * * cd /path-to-your-project && php artisan schedule:run >> /dev/null 2>&1

注:必须要关掉php.ini中的 proc_open和proc_get_status这两个函数,不然运行会无情报错

更多的调度频率设置选项和详细信息请参考官方文档

很赞哦! (0)

文章评论

站点信息