5
2

【Laravel】バッチ処理とは/簡単な実装

Last updated at Posted at 2024-03-24

バッチ処理とは

バックグラウンドで定期的に実行される一連の処理を実行するための機能。

以下のような自動化されたタスクを実行できる
・定期的なデータ処理
・データのインポート、エクスポート
・レポート生成

プログラムと指定日時を設定しておけば、夜間や土日など業務時間外でも処理が可能になります。

バッチはArtisanコマンドとして実装され、コンソールからだけでなく、Cronジョブやスケジューラなどのシステムスケジューリングツールによって実行できる、

メリット

・アプリケーションを効率化
・リソースの効率的な利用
・ヒューマンエラーの減少
・一貫性のある処理を確保

Laravelのバッチ処理には、キューとしてジョブを実行するための機能もある。

処理の流れ

1:バッチ処理のタスクを作成

バッチ処理で実行したいタスクを定義。
例)
・データベースの更新
・ファイルの処理
・APIの呼び出し

2:Artisanコマンドでファイル作成

タスクを実行するためのArtisanコンソールコマンドを作成。

php artisan make:command ファイル名

3:処理を実装

作成したコマンドクラス内に、バッチ処理の具体的なロジックを実装。
例)
・タスクの実行
・データの取得、保存

4:必要なサービスやライブラリの使用

バッチ処理に必要なサービスやライブラリがある場合は、それらを素養するためにLaravelの依存性注入(DI)機能を活用。

5:コマンドをスケジュール

定期的に実行する場合は、作成したコマンドをLaravelのスケジューラに登録。これにより、CronジョブやLaravelのスケジュール機能を使用して、定期的な実行が可能になる。

6:ログやエラーハンドリングを設定

バッチ処理の実行中に発生する可能性のあるエラーを適切に処理し、ログに記録するよう設定。

7:テストを作成

バッチ処理が期待どおりに機能することを確認するために、適切なテストを作成。

Artisanコマンドでファイル作成

php artisan make:command Test

app/Console/Commandsにファイルが生成される。
image.png

処理を実装

handle メソッド内にバッチ処理のロジックを記述

Test.php
<?php

namespace App\Console\Commands;

use Illuminate\Console\Command;
use Illuminate\Support\Facades\Log;

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

    /**
     * The console command description.
     *
     * @var string
     */
    protected $description = 'Test command';

    public function __construct()
    {
        parent::__construct();
    }

    /**
     * Execute the console command.
     */
    public function handle()
    {
        Log::info('実行しました。');
    }
}

protected $signature = 'app:test';コマンド名
protected $description = 'Test command';コマンド説明

コマンドが追加されたか確認

php artisan list

image.png

実行

php artisan app:test

結果:storage/laravel.log
image.png

タスクスケジュール定義

タスクスケジュールに登録すると、バッチコマンドで定時に処理が実行される。コンソールカーネルを使用すると、定期的なタスクを定義し、それらを実行するスケジュールを設定することができる。

app/COnsole/Kernel.php
<?php

namespace App\Console;

use Illuminate\Console\Scheduling\Schedule;
use Illuminate\Foundation\Console\Kernel as ConsoleKernel;

class Kernel extends ConsoleKernel


{
    /**
     * Define the application's command schedule.
     */
    protected function schedule(Schedule $schedule): void
    {
        $schedule->command('app:test')->everyTwoSeconds();
    }

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

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

schedule()に記述。

〇タスクスケジュールのオプション
https://readouble.com/laravel/10.x/ja/scheduling.html

定義できたか確認

php artisan schedule:list

参考

5
2
0

Register as a new user and use Qiita more conveniently

  1. You get articles that match your needs
  2. You can efficiently read back useful information
  3. You can use dark theme
What you can do with signing up
5
2