Blogブログ

TORAT | 2022.2.4

【Laravel】バッチ処理で業務を自動化しよう

  • Laravel
  • PHP

バッチ処理とは

一連のプログラムを自動的に実行する処理方式のことです。

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

バッチ処理の実装

Artisanコマンドの作成

$ php artisan make:command Sample

コマンド実行で、app/Console/Commands に Sample.php が作成されます。

コマンドの編集

// app/Console/Commands/Sample.php 
namespace App\Console\Commands;

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

class Excel extends Command
{
    /**
     * The name and signature of the console command.
     *
     * @var string
     */
    protected $signature = 'command:name'; // コマンド名を設定

    /**
     * The console command description.
     *
     * @var string
     */
    protected $description = 'コマンドの説明文を入力(任意)';

    /**
     * Create a new command instance.
     *
     * @return void
     */
    public function __construct()
    {
        parent::__construct();
    }

    /**
     * Execute the console command.
     *
     * @return int
     */
    public function handle()
    {
        // 実行させたい処理
        Log::info('実行しました。');
    }
}

Laravel5.4まではコマンドを作成後Kernel.php への登録が必要でしたが、5.5からは自動で登録されます。

// Kernel.php
protected function commands()
    {
        $this->load(__DIR__.'/Commands');

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

Kernel.php の上記の部分でCommandディレクトリごと読み込んでいます。

コマンドが追加されたか確認したいときは、次のコマンドを使用します。

$ php artisan list

先ほど入力した説明文はここで表示されます。

Available commands:
// コマンド名       //説明
command:name     コマンドの説明文を表示
sample                                         説明文hogehogehoge
test                                                説明文hogehoge

直接実行してみよう

$ php artisan command:name

先ほど設定したコマンド名で、コマンドを実行することができます。

storage/laravel.log を見て、ログが出力されていれば動いています。

//  storage/laravel.log
[2022-02-02 02:22:00] local.INFO: 実行しました。  
[2022-02-02 02:23:00] local.INFO: 実行しました。  
[2022-02-02 02:24:00] local.INFO: 実行しました。  

crontabに登録しよう

crontabに登録することで、自動で処理されるようになります。

$ crontab -e

上記のコマンドでcronの設定ファイルを呼び出し、以下の一文を追加します。

* * * * * cd /プロジェクトのフルパス && php artisan schedule:run >> /dev/null 2>&1

*****部分は、左から 分 時 日 月 曜日 を指定することができます。

分:0-59
時:0-23
日:1-31
月:1-12
曜日:0-7(0=日、1=月、2=火、3=水、4=木、5=金、6=土、7=日)

# 毎分実行
* * * * * echo 'hello'

# 毎時0分に実行
0 * * * * echo 'hello'

# 毎日9時00分に実行
0 9 * * * echo 'hello'

この記事を書いた人

TORAT 管理者

関連記事

Recommend愛されているブログ