はじめに
LaravelのプロジェクトにCron経由で動かせるバッチを作る方法を解説します。
まずはこの回でバッチ(Job)を作る方法を説明します。
やり方
コマンド機能
Laravelにはコマンド機能がありコマンドの追加が出来ます。
それを実行できるようにすればそのコマンドを呼び出すていでバッチの実行が出来ます。
スケジューラー機能
Laravelにはスケジューラー登録機能があり、
所定のファイルに設定を追加&決められた形式でCronに登録すれば定期的に処理を実行してくれます。
バッチの実行だけではなく、定期的なアプリやDBのクリーンアップにも使えます。
コマンド機能とスケジューラー機能を組み合わせることでCronからバッチの実行ができるようになります。
コードで解説
コマンド機能
コマンド作成コマンドでコマンドの作成
php artisan make:command <コマンド 名>
例)
xxxx@xxxxx command % php artisan make:command TestCommand Console command created successfully.
コマンドが成功すると以下ファイルが作成されます。
app/Console/Commands/<コマンド名>.php
例)app/Console/Commands/TestCommand.php
このファイルを編集してコマンドの設定をしていきます
$signature にコマンド名 >後々 php artisan コマンド名で コマンド実行できる
$descriptionにコマンドの説明書きを追加する > 下のコマンドの test commandのところ
php artisan list | grep command:testcommand
> command:testcommand test command
<?php namespace App\Console\Commands; use Illuminate\Console\Command; class TestCommand extends Command { /** * The name and signature of the console command. * * @var string */ //1.command名に書き換え protected $signature = 'command:testcommand'; /** * The console command description. * * @var string */ //2.commandの説明を追加 protected $description = 'test command'; /** * Create a new command instance. * * @return void */ public function __construct() { parent::__construct(); } /** * Execute the console command. * * @return int */ public function handle() { //3.とりあえず現在時間を表示するようにしてみた echo now(); return 0; } }
xxxxx@xxxxx command % php artisan command:testcommand
2020-10-11 23:47:00%
無事現在日時が表示されました。
スケジューラーの登録についてはこちらの記事をご確認ください
関連記事
後編

コメント