LoginSignup
0
0

➀バッチ処理機能、タスクスケジュール機能(Laravel)

Last updated at Posted at 2023-01-15

始めに

Laravelのバッチ処理機能を実装したので
備忘録として記事にしました。
2部構成となっております。(➀、➁)
 ➀:バッチ処理機能
 ➁:タスクスケジュール機能(Laravel機能)

バッチ処理:特定の日時に指定した処理を実行できる処理のこと。
タスクスケジュール機能:Laravel内でバッチ起動の日時を設定することができる機能

環境

開発環境 バージョン
Laravel 8.83
PHP 7.3
Server Amazon Linux

手順

1, Laravel内にcronとの連携処理を登録する
2, Laravel内に処理したい内容を実装する
3, cronに実行コマンドを登録、実行する

1, Laravel内にcronとの連携処理を登録する

バッチ登録用のファイルを作成します

// バッチ登録用のファイルを作成する
$ php artisan make:command BatchCommand
Console command created successfully.

// 確認する
ls -la ./app/Console/Commands/
-rw-r--r-- 1 userName 197121 1260 Nov 21 10:34 BatchCommand.php

作成したファイルを編集します

BatchCommand.php
namespace App\Console\Commands;

use Illuminate\Console\Command;
use App\Http\Controllers\BatchController;

class BatchCommand extends Command
{
    /**
     * The name and signature of the console command.
     *
     * @var string
     */
    // 実行するコマンドの名前です(引数も設定可能)
    protected $signature = 'command:batchTest';

    /**
     * The console command description.
     *
     * @var string
     */
    // コマンドの説明文です(適当でOK)
    protected $description = 'Command description';

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

    /**
     * Execute the console command.
     *
     * バッチコマンド処理内容(処理したい内容を書き込みます)
     */
    public function handle()
    {
        // 処理したいクラスをインスタンス生成します。
        $batch = new BatchController();
        $batch->test();
    }
}

手動でバッチ処理ができているかどうか確認します。
php artisan command:batchTest

2, Laravel内に処理したい内容を実装する

バッチ処理にて処理したいクラス、Controllerを作成します。

BatchController.php
namespace App\Http\Controllers;

use App\Http\Controllers\Controller;
use Illuminate\Http\Request;
use Illuminate\Support\Facades\Log;

/**
* バッチコントローラークラス
*/
class BatchController extends Controller
{

    /**
    * バッチ処理
    */
    public function test()
    {
        Log::debug(__FUNCTION__);
        Log::debug('バッチ処理完了しました');
    }

3, cronにコマンドを登録、実行する

* * * * * * 自分のプロジェクトまでのパス/artisan command:batchTest

「 * * * * * * 」にバッチ処理する日時を設定することができます。
( 参考資料:https://www.yoheim.net/blog.php?q=20190902

バッチ処理する日時をLaravel内で設定することも可能です。
こちらをご覧ください
↓ ↓ ↓

終わりに

最後まで読んでいただきありがとうございました。
ご指摘、ご意見ありましたらメッセージいただけますとありがたいです。
よろしくお願いします。

参考資料

Laravel バッチ処理の実行
https://qiita.com/hotate_chan/items/05f67096d8080b79390d

Laravelでバッチ(コマンド)処理を作成する方法のまとめ
https://codelikes.com/laravel-batch-command/

Laravelのタスクスケジューラを使う
https://qiita.com/toontoon/items/777c427345780411da8b

0
0
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
0
0