Laravel 定時任務排程 的 Artisan 命令排程
阿新 • • 發佈:2020-07-29
1、建立命令
php artisan make:command command_name --command=artisan_command_name # Explanation: # command_name: 生成的檔名 # artisan_command_name: php artisan 命令排程時的命令名稱 # 結果: 在 /app/Console/Commands/ 下生成名為 command_name.php 的檔案 # Example: # php artisan make:command LeaderMail --command=LeaderMail # 生成的檔名:LeaderMail # 排程時的命令名稱:LeaderMail
2、測試剛才生成的命令是否OK
php artisan LeaderMail
# Explanation:
# 沒有返回則表示成功。
# 因為 /app/Console/Commands/LeaderMail.php 的 handle 方法中沒有寫內容。寫了就會有返回。
3、編輯生成的檔案 /app/Console/Commands/LeaderMail.php 的 handle 方法
<?php namespace App\Console\Commands; use Illuminate\Console\Command; class LeaderMail extends Command { /** * The name and signature of the console command. * 用來描述命令的名字與引數 * @var string */ protected $signature = 'LeaderMail'; /** * The console command description. * 儲存命令描述 * @var string */ protected $description = 'Command description'; /** * Create a new command instance. * * @return void */ public function __construct() { parent::__construct(); } /** * Execute the console command. * 執行命令進行的操作 * @return mixed */ public function handle() { // 這裡是任務的具體處理 } }
4、編輯 App\Console\Kernel.php 檔案,新增排程
# 先到 /app/Console/Kernel.php 中 $commands 陣列中進行註冊。
# 然後在 /app/Console/Kernel.php 的 schedule 方法中定義排程任務。
<?php namespace App\Console; use App\Console\Commands\LeaderMail; use Illuminate\Console\Scheduling\Schedule; use Illuminate\Foundation\Console\Kernel as ConsoleKernel; class Kernel extends ConsoleKernel { /** * The Artisan commands provided by your application. * 你的應用程式提供的Artisan命令。 * @var array */ protected $commands = [ LeaderMail::class ]; /** * Define the application's command schedule. * * @param \Illuminate\Console\Scheduling\Schedule $schedule * @return void */ protected function schedule(Schedule $schedule) { // $schedule->command('inspire') // ->hourly(); // 每分鐘執行一次獲取領導信箱 // command() 排程時的命令名稱 // everyFiveMinutes() 排程規則 // appendOutputTo() 排程命令進行操作的返回結果記錄檔案 $schedule->command('LeaderMail')->everyFiveMinutes()->appendOutputTo(base_path('storage/crontab/log.log')); } /** * Register the commands for the application. * * @return void */ protected function commands() { $this->load(__DIR__ . '/Commands'); require base_path('routes/console.php'); } }
5、編輯機器的定時任務 crontab
# 複習
# crontab -l # 檢視
# crontab -e # 編輯
# crontab -r # 刪除所有
# 開始操作
crontab -e
# 然後新增以下語句
* * * * * path-to-your-php/bin/php /path-to-your-project/artisan schedule:run >> /dev/null 2>&1
# Explanation:
# path-to-your-php/bin/php 是你的PHP的絕對路徑,通過 which php 可以得到;
# path-to-your-project/artisan 是你專案中Laravel框架中根目錄下的 artisan 的絕對路徑;
6、如果想單獨寫出來也可以
* * * * * path-to-your-php/bin/php /path-to-your-project/artisan LeaderMail >> /dev/null 2>&1