laravel 5.5中定時任務實例


 

使用命令創建任務

php artisan make:command test

 

命令執行成功后會在項目app\Console\Commands目錄下面生成 test.php文件,內容如下

<?php

namespace App\Console\Commands;

use Illuminate\Console\Command;

class test extends Command
{
    /**
     * The name and signature of the console command.
     *
     * @var string
     */
    protected $signature = 'command:name';  // 此處代表laravel自動生成的名稱,下面執行的時候能用到

    /**
     * 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()
    {
        //  任務邏輯
    }
}

 

編輯  signature、description 屬性,增加閱讀性

protected $signature = 'demo'; 

protected $description = 'laravel5.5定時任務實例';  

 

編輯業務邏輯,這里只做演示 在test表中添加一條日期數據

public function handle()
{

     DB::table('test')->insert([
         'date' => date('Y-m-d H:i:s'),
     ]);

}

 

編輯項目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\test::class,    // 添加任務類
    ];

    /**
     * Define the application's command schedule.
     *
     * @param  \Illuminate\Console\Scheduling\Schedule  $schedule
     * @return void
     */
    protected function schedule(Schedule $schedule)
    {
        // $schedule->command('inspire')
        //          ->hourly();
                 
        $schedule->command('demo')->everyMinute();    // 設置任務每分鍾運行一次
    }

    /**
     * Register the Closure based commands for the application.
     *
     * @return void
     */
    protected function commands()
    {
        require base_path('routes/console.php');
    }
}

 

 開啟lavavel任務調度器(重點)

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

 該cron會每分鍾調用一次 laravel 命令調度器,然后laravel 會自動評估你的調度任務並運行到期的任務

 其中 path to project 為實際項目地址

 

修改cron為實際項目地址

* * * * * php /home/vagrant/code/artisan schedule:run >> /dev/null 2>&1 

 

至此定時任務配置完成,實際運行效果如下

 

系統每分鍾會執行一次laravel調度器,而laeravel則會分析Kernel.php中定義的任務規則執行到期的任務

 


免責聲明!

本站轉載的文章為個人學習借鑒使用,本站對版權不負任何法律責任。如果侵犯了您的隱私權益,請聯系本站郵箱yoyou2525@163.com刪除。



 
粵ICP備18138465號   © 2018-2025 CODEPRJ.COM