20分鐘學會Laravel的Schedule功能

Laravel的 Schedule 可以用來進行排程,處理清除 Log ,發送 Email 等工作。相對於透過請求來觸發程式的作法來說,是相對主動的技巧
實作流程
Step 1.把 Laravel 加入 CronJob
所謂的 Cron 指的是時間一到就會執行的機制,要實作 Schedule,就必須搭配 Cron
在Mac & Linux 上面的操作
crontab -e
接著 Terminal 將會切換到 Vim 介面,按下 i 來進入 Vim 的編輯模式,加入底下這一行
* * * * * cd /path-to-your-project && php artisan schedule:run >> /dev/null 2>&1
請把 /path-to-your-project
替換成你本地專案的路徑
這一行是在告訴電腦每分鐘都到這個專案目錄,執行php artisan schedule:run 這個指令,也就是處理排程工作的意思
貼完之後,按下esc鍵,接著輸入:wq,來離開vim的模式並進行儲存, 當你看到下面這個結果就表示你成功了啦
crontab: installing new crontab
如需確認是否成功,也可以輸入以下這個指令
crontab -l
順利的話,你應該會看到剛才所貼上的內容,就表示成功了
Step 2.定義一個命令
為了要執行排程,先把要作的事情封裝成一個命令是比較好的作法,也方便重用
新增一個命令
開啟Terminal ,輸入以下指令
php artisan make:command ServerReport
這個命令將會在 app/Console/Commands 資料夾內建立 LogReport.php,編輯檔案如下:
<?php
namespace App\Console\Commands;
use Illuminate\Console\Command;
use Log;
class ServerReport extends Command
{
/**
* 命令的名稱,用於呼叫命令.
*
* @var string
*/
protected $signature = 'server:report {data : The ID of the report}';
/**
* 命令的描述,用於列表顯示
*
* @var string
*/
protected $description = 'server report...';
public function __construct()
{
parent::__construct();
}
/**
* 命令的作業區.
*
* @return int
*/
public function handle()
{
$id = $this->argument('data');
if(!isset($id)){
Log::debug('server report...');
}else{
Log::debug('server report... data:' . $id);
}
}
}
Step 3.定義要排程的指令或流程
這裡示範是透過修改 Kernel.php 來進行排程,如果你個人偏好使用介面來管理排程,歡迎參考LARAVEL SCHEDULE 管理介面生成套件介紹
開啟 app/Console/Kernel.php ,在 schedule() 內加入要排程的命令或作業
//app/Console/Kernel.php
<?php
class Kernel extends ConsoleKernel
{
protected function schedule(Schedule $schedule)
{
$schedule->command('server:report 2')->dailyAt('22:39');
$schedule->command('server:report')->everyMinute();
}
}
關於排程的更多頻率選項,可以參考下面表單
方法 | 執行週期 |
---|---|
everyMinute() | 每分鐘 |
everyFiveMinutes() | 每五分鐘 |
everyTenMinutes() | 每十分鐘 |
everyFifteenMinutes() | 每十五分鐘 |
everyThirtyMinutes() | 每三十分鐘 |
hourly() | 每小時 |
hourlyAt(17) | 每小時的第十七分鐘 |
daily() | 每日午夜 |
dailyAt('13:00') | 每日 13:00 |
twiceDaily(1, 13) | 每日 01:00 與 13:00 |
weekly() | 每週六午夜 |
weeklyOn(1, '8:00') | 每週一上午 8:00 |
monthly() | 每月第一天的午夜 |
monthlyOn(4, '15:00') | 每月第四天的 15:00 |
quarterly() | 每季第一天的午夜 |
yearly() | 每年第一天的午夜 |
timezone('America/New_York') | 設定時區 |
如果需要輸入內容到檔案內,可以使用這個方法,像是appendOutputTo或emailOutputTo。詳情可參考
如果想要直接在 schedule 裡頭定義排程作業內容也是可以的,請參考這個例子:
$schedule->call(function () {
file_put_contents('time.log', \Carbon\Carbon::now());
})->everyMinute();