PHP Laravel9 Cron処理でデータのリセット処理をする

TOOLUU PHP Laravel9 Cron処理でデータのリセット処理をするコンテンツ

毎日午前0時に定期処理をしてデータをリセットしたい。
今までなら処理を書いてCronに登録するだけだったけどLaravelではすごく便利に使えるヘルパーがあるのでそれを使用します。 まず定期処理を書くプログラムのひな型を生成します。
# php artisan make:command RankingReset

/app/Console/Commands/RankingReset.phpにファイルが生成されるので、
$signatureにバッチの名称、handle()メソッドに処理を追記します。
<?php
namespace App\Console\Commands;

use Illuminate\Console\Command;

class RankingReset extends Command
{
    /**
     * The name and signature of the console command.
     *
     * @var string
     */
    protected $signature = 'batch:ranking_reset';

    /**
     * The console command description.
     *
     * @var string
     */
    protected $description = 'バッチ内容の説明文';

    /**
     * Execute the console command.
     *
     * @return int
     */
    public function handle()
    {
    	/* 定期処理を書く */
//        return Command::SUCCESS;
    }
}

/app/Console/Kernel.phpを編集して scheduleメソッドにスケジュールを追記。dailyを指定すると毎時0時に実行してくれる。
<?php
class Kernel extends ConsoleKernel
{
    /**
     * Define the application's command schedule.
     *
     * @param  \Illuminate\Console\Scheduling\Schedule  $schedule
     * @return void
     */
    protected function schedule(Schedule $schedule)
    {
        // $schedule->command('inspire')->hourly();
        $schedule->command('ranking_reset')->daily();
    }

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

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

/routes/console.phpを編集して追記
<?php
use Illuminate\Foundation\Inspiring;
use Illuminate\Support\Facades\Artisan;

/*
|--------------------------------------------------------------------------
| Console Routes
|--------------------------------------------------------------------------
|
| This file is where you may define all of your Closure based console
| commands. Each Closure is bound to a command instance allowing a
| simple approach to interacting with each command's IO methods.
|
*/
/*
Artisan::command('inspire', function () {
    $this->comment(Inspiring::quote());
})->purpose('Display an inspiring quote');
*/
Artisan::command('ranking_reset', function () {
    $this->comment(RankingReset::quote());
})->purpose('Display an RankingReset quote');


Laravelスケジュールのcronを追記する
# crontab -e
# Laravel Cron
* * * * * cd [Laravelディレクトリパス] && php artisan schedule:run >> /dev/null 2>&1

■参考資料
エンジニア婦人ノート様ありがとうございます。
https://engineer-lady.com/program_info/laravel-cron/

TOOLUU ツールの説明

PHP Laravel9 Cron処理でデータのリセット処理をするの記録をします

TOOLUU つかいかた例

PHP Laravel9 Cron処理でデータのリセット処理をするの記録をします