はじめに
こんにちは、エンジニアのkeitaMaxです。
今回はLaravel11を使用してバッチを作成していきたいと思います。
ファイル作成(コマンド作成)
以下のコマンドを使用してバッチを作成します。
php artisan make:command ExampleBatch
実行すると、src/app/Copnsole/Commands
ディレクトリ配下にExampleBatch.php
というファイルが作成されます。
<?php
namespace App\Console\Commands;
use Illuminate\Console\Command;
class ExampleBatch extends Command
{
/**
* The name and signature of the console command.
*
* @var string
*/
protected $signature = 'app:example-batch';
/**
* The console command description.
*
* @var string
*/
protected $description = 'Command description';
/**
* Execute the console command.
*/
public function handle()
{
//
}
}
これでコマンドが作成できました。
作成したコマンドを実行
作成したコマンドを実行するには以下のコマンドを実行します。
php artisan app:example-batch
app:example-batch
はExampleBatch.php
のprotected $signature = 'app:example-batch';
と書いてある部分です。ここを修正するとコマンドを変更することができます。
実行すると以下のようになります。
root@d720a6c8975b:/app# php artisan app:example-batch
root@d720a6c8975b:/app#
これだけだと本当に実行されているかわからないので、こんにちは
と実行した時にコンソールに出すようにしたいと思います。
ExampleBatch.php
ファイルを以下のように修正します。
<?php
namespace App\Console\Commands;
use Illuminate\Console\Command;
class ExampleBatch extends Command
{
/**
* The name and signature of the console command.
*
* @var string
*/
protected $signature = 'app:example-batch';
/**
* The console command description.
*
* @var string
*/
protected $description = 'Command description';
/**
* Execute the console command.
*/
public function handle()
{
$this->info("こんにちは"); // ←追加
}
}
これで先ほどのコマンドを実行すると以下のようになります。
root@d720a6c8975b:/app# php artisan app:example-batch
こんにちは
root@d720a6c8975b:/app#
しっかり実行されていることが確認できました。
1分に1回実行させるようにする
今作成したコマンドを1分に一回自動で実行されるようにしたいと思います。
routes.php/console.php
に以下のコードを追加します。
<?php
use Illuminate\Support\Facades\Schedule;
use Illuminate\Foundation\Inspiring;
use Illuminate\Support\Facades\Artisan;
Artisan::command('inspire', function () {
$this->comment(Inspiring::quote());
})->purpose('Display an inspiring quote')->hourly();
Schedule::command('app:example-batch')->everyMinute(); ← 追加
これで以下のコマンドでスケジュールを確認してみます。
php artisan schedule:list
root@d720a6c8975b:/app# php artisan schedule:list
0 * * * * php artisan inspire .................................................................................................. Next Due: 20 minutes from now
* * * * * 1s php artisan app:example-batch ......................................................................................... Next Due: 0 seconds from now
root@d720a6c8975b:/app#
* * * * * 1s php artisan app:example-batch
と書いてあるので、無事1分に1回実行するように修正できました。
おわりに
この記事での質問や、間違っている、もっといい方法があるといったご意見などありましたらご指摘していただけると幸いです。
最後まで読んでいただきありがとうございました!
参考