LoginSignup
0
0

さくらレンタルサーバーでLaravel11のCron設定をする

Posted at

はじめに

Laravel11にアップデートされCron処理の記述方法が変わったので、サーバー側の設定を含め紹介する

手順

  1. artisanコマンドの作成
  2. スケジュール設定を行う
  3. レンタルサーバー側でCron設定を行う

artisanコマンドの作成

下記コマンドでコマンドクラスを作成する

php artisan make:command {クラス名}

app/Console/Commands配下にクラスが作成される。

TestCommand.php
<?php

namespace App\Console\Commands;

use Illuminate\Console\Command;

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

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

    /**
     * Execute the console command.
     */
    public function handle()
    {
        echo "テストコマンドが実行されました。";
    }
}

各変数と関数の説明は以下の通り

変数・関数 説明
$signature 実行する際のコマンド名
$description php aritisan list をした際に表示されるコマンドの説明。
$handle 実際に実行したい処理内容

上記で作成したコマンドを実行するとこんな感じ

php artisan app:test-command
// 結果
テストコマンドが実行されました。

スケジュール設定を行う

作成したコマンドを指定した時間に実行するように、スケジュール設定を行う
以前はKernel.phpに記述していたが、Laravel11からは、routes/console.phpに記述を行う。

console.php
<?php

use Illuminate\Foundation\Inspiring;
use Illuminate\Support\Facades\Artisan;
use Illuminate\Support\Facades\Schedule; // Illuminate\Support\Facades配下のScheduleを使用

Artisan::command('inspire', function () {
    $this->comment(Inspiring::quote());
})->purpose('Display an inspiring quote')->hourly();

// 追加
Schedule::command('app:test-command')->everyMinute();

上記コードでは、everyMinute()で1分毎に実行するよう設定している。
5分毎、30分毎等メソッドが用意されているので、こちらを確認。

※この後のサーバー側でのCron設定で適切な設定をしないと、設定した時間通りに実行されないので注意

サーバー側でCron設定を行う

さくらインターネットにログイン後CRON設定の画面を開く

13261bb8b06d3fc6928942796be9117d.png

スケジュール追加を押すと下記画面が開くのでCRON設定を行う

80bcc8a224d98a7556b2b12624897297.png

実行コマンドには以下のコマンドを記述

cd /home/{ユーザー名}/www/{プロジェクト名}/; /usr/local/bin/php artisan schedule:run >> /dev/null 2>&1

実行日時には、php artisan schedule:runを実行したい感覚を設定する。
例: 月* 日* 時* 分*/30 曜日全て → 30分毎に実行

※レンタルサーバーによって、CRON設定の感覚が短すぎると、不可がかかるという理由から予告なく設定を消されてしまう可能性があるので注意する。さくらレンサバの場合は最低でも2分間隔でしか設定できない。

サーバー側のCRON設定を30分間隔、Laravel側のスケジュール設定を毎分にしても、30毎にしか指定したコマンドが実行されないので注意する。

参考

0
0
0

Register as a new user and use Qiita more conveniently

  1. You get articles that match your needs
  2. You can efficiently read back useful information
  3. You can use dark theme
What you can do with signing up
0
0