CRON一覧

Laravelでバッチ処理(Cron)を実行する

Laravel5を使用していてCronを動かし、バッチ処理を行うことがあると思います。

今回の記事では、Laravel5を使用しバッチ処理を行う方法について紹介します。

環境

  • CentOS 7.4
    • PHP 7.2.7
    • MySQL 5.7.22
    • Apache 2.4.6
  • Laravel 5.5/5.6

artisanコマンドの実行

バッチ処理を行うためには、Laravelのルートディレクトリで下記のartisanコマンドを打ちます。

php artisan make:command コマンド名

今回は、例として下記のコマンドを打ちます。

php artisan make:command HourlyUpdate

このコマンドを打つと、 app/Console/Commandsディレクトリに下記のような、Commandクラスを継承したHourlyUpdate(コマンド名)クラスが作成されます。

HourlyUpdate.php

<?php

namespace App\Console\Commands;

use Illuminate\Console\Command;

class HourlyUpdate extends Command
{
    /**
     * The name and signature of the console command.
     *
     * @var string
     */
    protected $signature = 'command:name';

    /**
     * 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()
    {
        //
    }
}
protected $signature = ‘command:name’;
protected $signature = 'command:name';

プログラムのコンソールコマンドの名前を指定しています。この文字列をartisanコマンドから渡す事で、処理が実行される事になります。
「name」がこの処理の識別子で、「command:」は、artisanコマンド上でのグルーピングを表しています。

今回は、下記のように$signatureを書き換えてしまいます。

protected $signature = 'hour:update';
protected $description = ‘Command description’;

下記の部分は、コマンドの説明です。自由に書き換えてしまいましょう。

protected $description = ‘Command description’;

今回は、下記のように書き換えます。

protected $description = ‘Send an hourly email to all the users’;

最後に、このコマンドを実行するたびに呼び出されるのがhandle()メソッドです。コマンドで実行するコード記載します。

public function handle()

今回のバッチ処理では、全てのユーザーにメールを送信する処理を行います。
handle()メソッドに下記のような記載をすることによりcronでバッチを動かすとusersテーブルに登録されているユーザー全てにメールが送信されます。

public function handle()

   {

       $user = User::all();

       foreach ($user as $a)

       {


           Mail::raw("This is automatically generated Hourly Update", function($message) use ($a)
           {

               $message->from('from@gmail.com');
               $message->to($a->email)->subject('Hourly Update');
           });
        }



   $this->info('Hourly Update has been send successfully');

   }

これで、コマンドが作り終わりました。
次に作成したコマンドを登録する必要があります。

コマンドの登録

コマンドを登録するために、”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 = [
        Commands\HourlyUpdate::class
    ];

    /**
     * Define the application's command schedule.
     *
     * @param  \Illuminate\Console\Scheduling\Schedule  $schedule
     * @return void
     * @return void
     */
    protected function schedule(Schedule $schedule)
    {
         $schedule->command('hour:update')
                  ->hourly();
    }

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

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

“protected $commands”は登録するコマンドを指定する場所です

    protected $commands = [
        Commands\HourlyUpdate::class
    ];
schedule()メソッド

“schedule()”メソッドは、指定した間隔で実行されるコマンドを指定する場所です。

    protected function schedule(Schedule $schedule)
    {
         $schedule->command('hour:update')
                  ->hourly();
    }

これで、作成したコマンドの登録が終わりました。
Laravelのルートディレクトリに行き、下記のコマンドを打ってみてください。

$ php artisan list

リストの中に、下記のような内容があるはずです。

 hour
 hour:update          Send an hourly email to all the users

下記のように、$signature = ‘command:name’;で指定した内容でartisanコマンドを叩くことができるようになります。

$ php artisan 'hour:update'
Hourly Update has been send successfully

artisanコマンドにスケジュールを登録

今回、例として示したコマンドは、1時間に一回処理を行う処理を作成しています。それを実現するために、app/Console/Kernel.phpファイルのschedule()メソッドで、下記のように指定しました。

protected function schedule(Schedule $schedule)
{
    $schedule->command('hour:update')
             ->hourly();
}

$schedule->command(‘hour:update’)はどのコマンドを実行するかを示しており、->hourly();は時間の間隔を示しています。
この例では、時間単位で時間間隔を設定していますが、公式のLaravelのドキュメントに記載されているように、もっと多くの時間を設定できます。下記にLaravel5で指定できるバッチを実行する時間のオプションを示します。

スケジュールのオプション
->cron(‘* * * * * *’); CRON記法によるスケジュール
->everyMinute(); 毎分タスク実行
->everyFiveMinutes(); 5分毎にタスク実行
->everyTenMinutes(); 10分毎にタスク実行
->everyThirtyMinutes(); 30分毎にタスク実行
->hourly(); 毎時タスク実行
->hourlyAt(17); 一時間ごと、毎時17分にタスク実行
->daily(); 毎日深夜12時に実行
->dailyAt(’13:00′); 毎日13:00に実行
->twiceDaily(1, 13); 毎日1:00と13:00時に実行
->weekly(); 毎週実行
->monthly(); 毎月実行
->monthlyOn(4, ’15:00′); 毎月4日の15:00に実行
->quarterly(); 四半期ごとに実行
->yearly(); 毎年実行
->timezone(‘America/New_York’); タイムゾーン設定

Cronへスケジュールを登録

次にCronへスケジュールを登録します。下記の内容をCronへ登録します。

* * * * * php /var/www/your_project_folder_name/artisan schedule:run >> /dev/null 2>&1

上記の記述でlaravelスケジューラが毎分実行され、その都度、実行するべきタスクがあれば実行されます。また、Cronジョブのログは、
“/var/log/cron”で確認することができます。

まとめ

WEBをやっているとCronを使用し、バッチ処理をする機会は多々あると思います。
Laravelを使用し、バッチ処理を行おうと考えている方は、ぜひ参考にしてみてください。