LoginSignup
21
28

More than 1 year has passed since last update.

Laravel バッチ処理の実行

Last updated at Posted at 2021-07-12

プログラムからのバッチ処理実行

Laravel ではバッチ処理を artisan を使用して実行する事が出来ます。
具体的にはcronに実行コマンドを登録するプログラムから実行する、という方法があるのでこれらのやり方を記します。
※バッチプログラムの追加から登録、実行まで

バッチ処理プログラムの追加

まずはバッチ処理を記述するファイル(PHPファイル)を以下のコマンドで作成します。

$ php artisan make:command BatchTest
Console command created successfully.

実行すると ./app/Console/Commands/ 配下に BatchTest,php が作成されます。

ls -la ./app/Console/Commands/
-rw-rw-r-- 1 vagrant vagrant    675  7月 12 11:55 BatchTest.php

出来上がったファイルを開いてみます

BatchTest.php
<?php

namespace App\Console\Commands;

use Illuminate\Console\Command;

class BatchTest 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 mixed
     */
    public function handle()
    {
        //
    }
}

こんな感じになっているので、以下の修正をしてみます。

BatchTest.php
    protected $signature = 'testBatch:testDayo';
    protected $description = 'コマンド実行のテストだよ';

    public function handle()
    {
        echo date("YmdHis");
    }

\$signature はこのプログラムのサイン?識別子みたいなものです。英数字で指定しましょう。
\$description はこのプログラムの説明文です。日本語でもOKです。
これらは、次の「バッチ処理の実行」で確認出来ます。

バッチ処理の実行

確認

以下のコマンドを実行します

$ php artisan list

すると、出力され結果の中に以下のものが含まれています。

testBatch
  testBatch:testDayo             コマンド実行のテストだよ

先ほど指定した \$signature と \$description が使用されています。
では、次でこのプログラムを実行します。

実行

以下のコマンドを実行します。

$ php artisan testBatch:testDayo

$php artisan + $signatureで指定した文字列 です。

実行結果

$ php artisan testBatch:testDayo
20210712151545

以下のコードが実行されました。

BatchTest.php
    public function handle()
    {
        echo date("YmdHis");
    }

cron登録

では、このプログラムはバッチという位置づけなので、cronに登録してみます。
※windowsであればタスクスケジューラー

crontab に以下を追加

00 * * * * php artisanまでのパス/artisan testBatch:testDayo

これで毎時0分にプログラムが実行されます。

プログラムから実行

cron からではなくプログラムから実行するためには以下のように記述します。

use Artisan;

~~処理を実行したいところ~~
Artisan::call('testBatch:testDayo');

Artisanクラスを使う事でコマンドを記述して実行、とは異なる実装が可能です。

21
28
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
21
28