Laravelのバッチ処理 – cronみたいなやつ

cronの処理を使わないでLaravelのバッチ処理を使った方が幸せです。汎用的な技術にはならないのが残念ですね。Laravel限定。
Laravelのバッチ処理の流れは、artisanコマンドを作成する、それをLaravelに登録する、以上というものになります。普段使っているLaravelのartisanコマンドも同様にあらかじめ作成されているものなので、逆にいうと毎日どこかの時間でキャッシュをクリアするみたいなこともできます。

artisanコマンド作成

サンプルのバッチを作成してみます。

$ php artisan make:command SampleBatch
(./vendor/bin/sail artisan make:command SampleBatch)

新規でapp/Console/Commands/SampleBatch.phpが作成されます。Command以下は用途によって適当なディレクトリを作成しておくとよいと思います。
こういうファイルが作成されます。

<?php

namespace App\Console\Commands;

use Illuminate\Console\Command;

class SampleBatch 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 int
   */
  public function handle()
  {
    return 0;
  }
}

最初から作成しなくても、Laravelの中のサービスとかモデルとかそういうものが使えるので非常に助かります。

Hello world的なもので実行してみる

最初にコマンド名を登録します。プロパティーの$signatureに追加します。デフォルトではcommand:nameになっていると思います。

protected $signature = 'command:sample';

これで、$ php artisan list | grep commandで登録されているか確認します。

...
Available commands:
  help                 Display help for a command
  list                 List commands
 command
  command:sample       Command description ←追加されています。
  make:command         Create a new Artisan command
  schedule:list        List the scheduled commands
...

この時点でコマンドの中身が空ですが、実行できるようになっています。

$ php artisan command:sample
(./vendor/bin/sail artisan command:sample)

中身を書く

あとはコントローラと同じく実行したい内容をhandle()のメソッドとして記述するだけです。もちろんコマンドの正体はただのクラスなので、コンストラクタやプロパティも使えます。

public function handle()
  {
    echo "sample commnad\n";
    \logger("sample commnad");
    return 0;
  }

これで実行すると、コンソールには指定の文字列が表示され、またロギングされます。

artisanコマンドをバッチとして登録する

最後にcronのようなLaravelの仕組みに登録します。これはホスト側のcronを1分おきに登録し、その親玉で実行したバッチが子の処理をするという仕組みになっています。レンタルサーバーのようにcronの設定が数個限定だったりする場合はLaravelの方で無制限にバッチ処理ができるのでとてもよいです。
公式的にはタスクスケジューラーという名前らしい。https://readouble.com/laravel/5.8/ja/scheduling.html

スケジュールタスクは全部App\Console\Kernelクラスのscheduleメソッドの中に定義します。

    protected function schedule(Schedule $schedule)
    { 
      # https://readouble.com/laravel/5.8/ja/scheduling.html
      // $schedule->command('inspire')->hourly();
      $schedule->command('command:sample')->everyMinute();
    }

これでOK

中心になるバッチをたたきます。このコマンドをcronに登録します。

php artisan schedule:run
(./vendor/bin/sail artisan  schedule:run)

ロリポでタスクスケジューラーを設定するには

ロリポのcronは管理画面でファイルを指定しないといけないので、コマンドを記述することができないです。しかたがないので、シェルを書いてそれを実行させます。


  • News

  • Categories

  • Tags

  • Archives

  • Page index