Laravel 12 指令程式及自動排程設置指南 for AlmaLinux OS

在 Laravel 12,作業系統 AlmaLinux OS 設定程式的自動排程,從 Laravel command 程式的產生,設定執行排程 console.php,到 Linux 底層 crontab 與 Laravel 自動排程的掛勾。
command 程式
先進入到 Laravel 12 的專案目錄內,產生 command 程式:
php artisan make:command RunMyProgram
在路徑 /usr/share/nginx/api/app/Console/Commands/RunMyProgram.php 會產生 command 程式:
$signature
:呼叫此程式的名稱。$description
:此程式的描述。handle()
:程式碼寫在此 function 內。
<?php
namespace App\Console\Commands;
use Illuminate\Console\Command;
use Illuminate\Support\Facades\Log;
class RunMyProgram extends Command
{
/**
* The name and signature of the console command.
*
* @var string
*/
protected $signature = 'app:run-my-program';
/**
* The console command description.
*
* @var string
*/
protected $description = 'Command description';
/**
* Execute the console command.
*/
public function handle()
{
Log::info('app:run-my-program 已執行');
$this->info('app:run-my-program 已執行');
}
}
手動執行此程式:
php artisan app:run-my-program
app:run-my-program 已執行
設定執行排程 console.php
在路徑 /usr/share/nginx/api/routes/console.php 新增要自動執行排程的 'app:run-my-program' 程式:
- everyMinute():每分鐘執行一次。
<?php
use Illuminate\Foundation\Inspiring;
use Illuminate\Support\Facades\Artisan;
Artisan::command('inspire', function () {
$this->comment(Inspiring::quote());
})->purpose('Display an inspiring quote');
Schedule::command('app:run-my-program')
->everyMinute();
設定 crontab
在結尾設定以下指令,來讓 Linux 底層的 crontab 與 Laravel 掛勾:
sudo vim /etc/crontab
SHELL=/bin/bash
PATH=/sbin:/bin:/usr/sbin:/usr/bin
MAILTO=root
# For details see man 4 crontabs
# Example of job definition:
# .---------------- minute (0 - 59)
# | .------------- hour (0 - 23)
# | | .---------- day of month (1 - 31)
# | | | .------- month (1 - 12) OR jan,feb,mar,apr ...
# | | | | .---- day of week (0 - 6) (Sunday=0 or 7) OR sun,mon,tue,wed,thu,fri,sat
# | | | | |
# * * * * * user-name command to be executed
* * * * * nginx cd /usr/share/nginx/api && php artisan schedule:run >> /dev/null 2>&1
確認自動排程
查看有沒有這支 command 程式:
php artisan list | grep run-my-program
app:run-my-program Command description
使用指令 tail -f
來確認資料輸出到 log 檔的情況:
tail -f storage/logs/laravel.log
[2025-08-27 05:41:21] local.INFO: app:run-my-program 已執行
[2025-08-27 05:45:02] local.INFO: app:run-my-program 已執行
[2025-08-27 05:47:02] local.INFO: app:run-my-program 已執行
[2025-08-27 05:48:03] local.INFO: app:run-my-program 已執行
參考

本著作係採用創用 CC 姓名標示-相同方式分享 3.0 台灣 授權條款授權.