schedule 與 commands 在 Laravel 中用來定義應用程式的排程與自訂 Artisan 命令。
schedule
commands
App\Console\Kernel.php
$schedule
php artisan make:command
可以寫在 app/Console/Commands 下,需繼承 Illuminate\Console\Command,或使用 Artisan 命令建立:
app/Console/Commands
Illuminate\Console\Command
php artisan make:command FooBarCommand
在 $signature 屬性中定義指令名稱(如 foo:bar),$description 定義說明文字,邏輯撰寫於 handle() 方法中。
$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); }
protected function commands() { $this->load(__DIR__.'/Commands'); $this->commands([ FooBarCommand::class, ]); }
load()
$this->commands()
使用 cron 定時執行 php artisan schedule:run。 若使用容器化(如 OnePanel),需進入容器並設定對應指令。
php artisan schedule:run
docker exec -it onepanel bash
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 時間格式為:分 時 日 月 星期 * * * * * 表示每分鐘執行一次。
* * * * *
Laravel 排程與自訂 Artisan 命令(Schedule / Commands)
schedule與commands在 Laravel 中用來定義應用程式的排程與自訂 Artisan 命令。App\Console\Kernel.php中的schedule方法透過$schedule變數定義排程。commands方法則用來載入應用程式的自訂 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 設定
新增排程設定:
* * * * * cd /path/to/your/laravel/project && php artisan schedule:run >> /dev/null 2>&1OnePanel 中範例:
* * * * * docker exec -i --user=www-data --workdir=/data/wwwroot/www.lohaslife.cc/httpdocs php80 php artisan schedule:run