Blog スタッフブログ

Laravel システム開発

[Laravel]Cron処理の仕方

システム開発担当のTFです。

やり方

  • app\Console\Commands\ 内に、cronで実行するコマンドを作成する
  • app\Console\Kernel.php に作成したコマンドのスケジュールを登録する
  • サーバーのcronを設定し、毎分 スケジュールを動かすようにする

参考

  Laravel 10.x タスクスケジュール

サンプル

<?php

namespace App\Http\Controllers;

use Illuminate\Support\Facades\DB;

class TaskTestController extends Controller
{
    public static function test()
    {
		// 実行したい処理を記述

    }
}
<?php

namespace App\Console\Commands;

use Illuminate\Console\Command;
use Illuminate\Support\Facades\Storage;

use App\Http\Controllers\TaskTestController;

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

    /**
     * The console command description.
     *
     * @var string
     */
    protected $description = 'test';

    /**
     * Create a new command instance.
     *
     * @return void
     */
    public function __construct()
    {
        parent::__construct();
    }

    /**
     * Execute the console command.
     *
     * @return mixed
     */
    public function handle()
    {
        // 実行したい処理を呼ぶ
		TaskTestController::test();
    }
}
<?php

namespace App\Console;

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

class Kernel extends ConsoleKernel
{
    // 作成したコマンドのクラス登録
	protected $commands = [
        \App\Console\Commands\TestCommand::class,
    ];
	
	/**
     * Define the application's command schedule.
     */
    protected function schedule(Schedule $schedule): void
    {
		// 作成したコマンドのスケジュール登録
		$schedule->command('command:test')->dailyAt('00:00');
    }

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

        require base_path('routes/console.php');
    }
}
# cron設定
# phpや artisan のパスは環境によって変更 し、毎分で設定する
* * * * * /usr/bin/php8.1 /このサイトのパス/artisan schedule:run >> /dev/null 2>&1