Laravel 排程與自訂 Artisan 命令(Schedule / Commands)

schedulecommands 在 Laravel 中用來定義應用程式的排程與自訂 Artisan 命令。

  • App\Console\Kernel.php 中的 schedule 方法透過 $schedule 變數定義排程。
  • commands 方法則用來載入應用程式的自訂 Artisan 命令。
  • 建立 Artisan 命令可使用 php artisan make:command 指令。

Schedule

建立任務

可以寫在 app/Console/Commands 下,需繼承 Illuminate\Console\Command,或使用 Artisan 命令建立:

php artisan make:command FooBarCommand

任務範例

$signature 屬性中定義指令名稱(如 foo:bar),$description 定義說明文字,邏輯撰寫於 handle() 方法中。

<?php

namespace App\Console\Commands;

use Illuminate\Console\Command;

class FooBarCommand extends Command
{
    protected $signature = 'foo:bar';
    protected $description = 'Example command description';

    public function handle()
    {
        // your command logic here
    }
}

app/Console/Kernel.php 中定義排程

protected function schedule(Schedule $schedule)
{
    // 每天凌晨 1 點執行 foo:bar
    $schedule->command('foo:bar')->dailyAt('01:00');

    // 每分鐘第 10 秒執行 foo:bar
    $schedule->command('foo:bar')->everyMinute()->seconds(10);
}

Commands

app/Console/Kernel.php 中註冊

protected function commands()
{
    $this->load(__DIR__.'/Commands');

    $this->commands([
        FooBarCommand::class,
    ]);
}
  • load() 方法用來載入目錄下的所有命令。
  • $this->commands() 方法註冊指定命令至 Artisan 指令集中。

Linux 主機設定(Cron)

使用 cron 定時執行 php artisan schedule:run
若使用容器化(如 OnePanel),需進入容器並設定對應指令。

進入容器範例(OnePanel)

docker exec -it onepanel bash

編輯 crontab 設定

crontab -e

新增排程設定:

* * * * * cd /path/to/your/laravel/project && php artisan schedule:run >> /dev/null 2>&1

OnePanel 中範例:

* * * * * docker exec -i --user=www-data --workdir=/data/wwwroot/www.lohaslife.cc/httpdocs php80 php artisan schedule:run

Cron 時間格式為:分 時 日 月 星期
* * * * * 表示每分鐘執行一次。