[0018]バッチ処理 Console
■コマンドの作成
この例のLalavelフレームワークのバージョンは5.5です。
artisanコマンドを実行し、コマンド(Command)を作成します。
コマンドプロンプト
% php artisan make:command MstGetCommand
マスタをGETするバッチなので、名前はMstGetCommandにしました。任意で決めることができます。プロジェクト配下でartisanコマンドを実行すると、app/Console/CommandsにMstGetCommand.phpが作成されます。
MstGetCommand.phpを編集します。$signatureにコマンドの名前、$descriptionに説明、handleにバッチ処理の中身を記述します。
MstGetCommand.php
<?php
namespace App\Console\Commands;
use Illuminate\Console\Command;
use Log;
class MstGetCommand extends Command
{
/**
* The name and signature of the console command.
*
* @var string
*/
protected $signature = 'batch:MstGet';
/**
* The console command description.
*
* @var string
*/
protected $description = 'MstGet';
/**
* Create a new command instance.
*
* @return void
*/
public function __construct()
{
parent::__construct();
}
/**
* Execute the console command.
*
* @return mixed
*/
public function handle()
{
$date = date('Y-m-d');
//アクセスログ保持
Log::info("batch:MstGet start".$date);
}
}
アクセスログを書き込むだけの処理しか記述していないサンプルです。
■Kernel設定
作成したMstGetCommand.phpを呼び出す設定をするため、app/Console/Kernel.phpを編集します。
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\MstGetCommand::class,
];
/**
* Define the application's command schedule.
*
* @param \Illuminate\Console\Scheduling\Schedule $schedule
* @return void
*/
protected function schedule(Schedule $schedule)
{
$schedule->command('batch:MstGet')->cron('10 11 * * * *');
}
/**
* Register the commands for the application.
*
* @return void
*/
protected function commands()
{
$this->load(__DIR__.'/Commands');
require base_path('routes/console.php');
}
}
commandsに"\App\Console\Commands\MstGetCommand::class"を追加し、scheduleに設定します。
今回はCRON記法によるスケジュールをしました。その他たくさんの方法は以下を参考にしています。
https://readouble.com/laravel/5.5/ja/scheduling.html#schedule-frequency-options
■cronの設定
WEBサーバにSSH接続し、cronの設定を行います。
コマンドプロンプト
% crontab -e
cron設定に1行追加します
* * * * * php /var/www/vhost/XXX/artisan schedule:run >> /dev/null 2>&1
/var/www/vhost/XXXはプロジェクト直下までのディレクトリです。ご自身の環境に合わせて変更してください。
cron('10 11 * * * *')にしていましたので、11:10にバッチが動き、無事ログが書き込まれました。
Lalavel5.7では5段階、min (0 - 59)、hour (0 - 23)、day of month (1 - 31)、month (1 - 12)、day of week (0 - 7) (Sunday=0 or 7)でした。
Lalavel5.7ではcron('10 11 * * *')になります。