歡迎來到手把手復制執行環節
步驟目錄
- 第一步生成呼叫檔案
- 第二步定義調度
- 第三步啟動調度器
第一步生成呼叫檔案
執行以下命令
php artisan make:command 你的命名
該命令會在 app/Console/Commands 目錄下創建 你命名的檔案
下面是我對該檔案的理解
<?php
namespace App\Console\Commands;
use Illuminate\Console\Command;
use App\Models\User;
use Illuminate\Support\Facades\Log;
class Test Command
{
/**
* The name and signature of the console command.
*
* @var string
*/
//此處代表名稱,呼叫時使用
protected $signature = 'command:Test';
/**
* The console command description.
*
* @var string
*/
//對定時任務的描述
protected $description = '這是一個測驗';
/**
* Create a new command instance.
*
* @return void
*/
public function __construct()
{
parent::__construct();
}
/**
* Execute the console command.
*
* @return mixed
*/
public function handle()
{
/*
* 這是是執行任務
*/
//我們可以在這里做我們需要的操作
$user = User::find(1);
$user->update(['name'=>'成功修改']);
Log::info('定時任務執行');
}
}
第二步定義調度
檔案修改好以后我們需要在App\Console\Kernel== 類的 schedule 方法中定義所有調度任務
<?php
namespace App\Console;
use DB;
use Illuminate\Console\Scheduling\Schedule;
use Illuminate\Foundation\Console\Kernel as ConsoleKernel;
class Kernel extends ConsoleKernel
{
/**
* 應用提供的 Artisan 命令
*
* @var array
*/
protected $commands = [
//這里寫上你生成的檔案路徑
\App\Console\Commands\Test::class,
];
/**
* 定義應用的命令調度
*
* @param \Illuminate\Console\Scheduling\Schedule $schedule
* @return void
*/
protected function schedule(Schedule $schedule)
{
//該處執行調度
$schedule->command('command:Test')->monthly();
}
}
以下為調度頻率設定函式
->cron('* * * * *'); 在自定義Cron調度上運行任務
->everyMinute(); 每分鐘運行一次任務
->everyFiveMinutes(); 每五分鐘運行一次任務
->everyTenMinutes(); 每十分鐘運行一次任務
->everyThirtyMinutes(); 每三十分鐘運行一次任務
->hourly(); 每小時運行一次任務
->daily(); 每天凌晨零點運行任務
->dailyAt('13:00'); 每天13:00運行任務
->twiceDaily(1, 13); 每天1:00 & 13:00運行任務
->weekly(); 每周運行一次任務
->monthly(); 每月運行一次任務
->monthlyOn(4, '15:00'); 每月4號15:00運行一次任務
->quarterly(); 每個季度運行一次
->yearly(); 每年運行一次
->timezone('America/New_York'); 設定時區
第三步啟動調度器
只需將以下 Cron 專案添加到服務器
* * * * * /你php的絕對路徑 /你專案的根目錄絕對路徑/artisan schedule:run >> /dev/null 2>&1
操作如下
命令列輸入crontab -e
輸入i可以進入編輯狀態,可輸入任務代碼,
在最后面添加
* * * * * /你php的絕對路徑 /你專案的根目錄絕對路徑/artisan schedule:run >> /dev/null 2>&1
例如
* * * * * /www/server/php/74/bin/php /www/wwwroot/test/artisan schedule:run >> /dev/null 2>&1
回車換行以后
先按Esc鍵,然后輸入:wq 保存檔案
然后執行命令
php artisan schedule:run
定時任務調度即可順利執行
轉載請註明出處,本文鏈接:https://www.uj5u.com/qita/242934.html
標籤:其他
