[Laravel]バッチ処理のタスクスケジュール

今回はLaravelでバッチ処理をタスクスケジュールで実行する方法を紹介します。

コマンドで実行するPHPクラスの作成

以下のコマンドを使用して作成をおこないます。

php artisan make:command BatchTest --command="batchtest"

上記のコマンドを実行すると以下の階層に「BatchTest」クラスが生成されます。

app/Console/Commands/BatchTest.php

生成されたクラスの中身は以下の通りです。

<?php

namespace App\Console\Commands;

use Illuminate\Console\Command;

class PointTest extends Command
{
    /**
     * The name and signature of the console command.
     *
     * @var string
     */
    protected $signature = 'batchtest';

    /**
     * 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()
    {

        //ここに処理を記述します。
		echo 'batch test';

    }
}

コマンドで実行する処理はhandleファンクション内に記述します。

今回は「batch test」を出力する処理を追加しました。

コマンドを実行するにはapp/Console/Kernel.phpに上記のクラスを追加する必要があります。


<?php

namespace App\Console;

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

class Kernel extends ConsoleKernel
{
    /**
     * The Artisan commands provided by your application.
     *
     * @var array
     */
    protected $commands = [
	
        //ここに作成したクラスを追加します。
        \App\Console\Commands\BatchTest::class,
    
	];

    /**
     * Define the application's command schedule.
     *
     * @param  \Illuminate\Console\Scheduling\Schedule  $schedule
     * @return void
     */
    protected function schedule(Schedule $schedule)
    {
        // $schedule->command('inspire')
        //          ->hourly();

    }

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

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

以上の追加ができたら、実際にコマンドから実行できるか試してみます。

$ php artisan batchtest
batch test

無事、実行できることが確認できました。

次回はLinuxのcrontabに登録をおこない、指定した日時に自動的にバッチ処理が実行されるように設定します。

金曜日担当: nishida



アプリ関連ニュース

お問い合わせはこちら

お問い合わせ・ご相談はお電話、またはお問い合わせフォームよりお受け付けいたしております。

tel. 06-6454-8833(平日 10:00~17:00)

お問い合わせフォーム