LoginSignup
15
19

More than 3 years have passed since last update.

【Laravel】バッチ処理、Cronのタスクスケジュール実行まで

Posted at

今日も張り切って備忘録。
バッチの理解を深める為、簡単な処理を実装してみた。

環境

PHP 7.3.8
Laravel 6.18.35

バッチ処理を書く

Userテーブルに登録されているユーザー数を取得するバッチを作成する。
まずコマンドクラスを生成する。

php artisan make:command UserCount

コマンドを実行すると、ファイルがapp/Console/Commands/の直下に作成される。

UserCountCommand.php
<?php

namespace App\Console\Commands;

use Illuminate\Console\Command;
//あとでログを出力する処理もいれるので
use Illuminate\Support\Facades\Log;
//操作するテーブルを読み込む
use App\User;

class UserCountCommand extends Command
{
    /**
     * The name and signature of the console command.
     *
     * @var string
     */

    //コマンドの名前を設定
    protected $signature = 'user:count';

    /**
     * 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 mixed
     */
    public function handle()
    {
      //標準出力&ログに出力するメッセージのフォーマット
      $message = '[' . date('Y-m-d h:i:s') . ']UserCount:' . User::count();

      //INFOレベルでメッセージを出力
      $this->info( $message );
      //ログを書き出す処理はこちら
      Log::setDefaultDriver('batch');
      Log::info( $message );
    }
}

これでバッチが完成

ターミナルでコマンドを実行

php artisan user:count

こんな感じで表示されればOK
スクリーンショット 2020-09-07 21.52.22.png

バッチをCronで定時実行する

crontabにエントリーを記述する事で、エントリーの内容にそって定期的にバッチ処理を実行する事が出来ます。

参考:Laravelのタスクスケジュール(cron)を使いこなす

というわけで、crontabをvimコマンドで編集します。

$crontab -e

以下の1行を追加するだけでOK

* * * * * php /path_to_your_project/artisan schedule:run 1>> /dev/null 2>&1

$commands に作成したバッチコマンドを追加するのと、scheduleにバッチのスケジュールを記載する。

app/Console/Kernel.php
class Kernel extends ConsoleKernel
{
    /**
     * The Artisan commands provided by your application.
     *
     * @var array
     */
    protected $commands = [
        \App\Console\Commands\UserCountCommand::class
    ];

    /**
     * Define the application's command schedule.
     *
     * @param  \Illuminate\Console\Scheduling\Schedule  $schedule
     * @return void
     */
    protected function schedule(Schedule $schedule)
    {
        // user:countコマンドを毎分実行する
        $schedule->command('user:count')->everyMinute();
    }

ログファイルを見てみると

スクリーンショット 2020-09-07 22.07.56.png
ちゃんと1分おきに実行されていますね!

15
19
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
15
19