cronの処理を使わないでLaravelのバッチ処理を使った方が幸せです。汎用的な技術にはならないのが残念ですね。Laravel限定。
Laravelのバッチ処理の流れは、artisanコマンドを作成する、それをLaravelに登録する、以上というものになります。普段使っているLaravelの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の中のサービスとかモデルとかそういうものが使えるので非常に助かります。
最初にコマンド名を登録します。プロパティーの$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;
}
これで実行すると、コンソールには指定の文字列が表示され、またロギングされます。
最後に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は管理画面でファイルを指定しないといけないので、コマンドを記述することができないです。しかたがないので、シェルを書いてそれを実行させます。