1、創建一個命令
php artisan make:command TestCommand
執行成功后會提示:
Console command created successfully.
生成了一個新的命令文件
App\Console\Commands\TestCommand.php
<?php namespace App\Console\Commands; use Illuminate\Console\Command; class TestCommand extends Command { /** * The name and signature of the console command. * 命令名稱(執行時需要用到) * @var string */ protected $signature = 'test'; /** * 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 int */ public function handle() { echo 123123; echo PHP_EOL; exit; } }
2、配置console的Kernel
<?php namespace App\Console; use App\Console\Commands\TestCommand; use Illuminate\Console\Scheduling\Schedule; use Illuminate\Foundation\Console\Kernel as ConsoleKernel; class Kernel extends ConsoleKernel { /** * The Artisan commands provided by your application. * * @var array */ protected $commands = [ // TestCommand::class, ]; /** * Define the application's command schedule. * * @param \Illuminate\Console\Scheduling\Schedule $schedule * @return void */ protected function schedule(Schedule $schedule) { // $schedule->command('inspire')->hourly(); $schedule->command('test')->everyMinute(); } /** * Register the commands for the application. * * @return void */ protected function commands() { $this->load(__DIR__.'/Commands'); require base_path('routes/console.php'); } }
3、執行命令
手動執行:
php artisan test(命令名稱)
自動執行:
php artisan schedule:run
定時執行:crontab添加
php artisan schedule:run
->cron('* * * * *');
自定義 Cron 計划執行任務
->everyMinute();
每分鍾執行一次任務
->everyFiveMinutes();
每五分鍾執行一次任務
->everyTenMinutes();
每十分鍾執行一次任務
->everyFifteenMinutes();
每十五分鍾執行一次任務
->everyThirtyMinutes();
每三十分鍾執行一次任務
->hourly();
每小時執行一次任務
->hourlyAt(17);
每小時第 17 分鍾執行一次任務
->daily();
每天 0 點執行一次任務
->dailyAt('13:00');
每天 13 點執行一次任務
->twiceDaily(1, 13);
每天 1 點及 13 點各執行一次任務
->weekly();
每周日 0 點執行一次任務
->weeklyOn(1, '8:00');
每周一的 8 點執行一次任務
->monthly();
每月第一天 0 點執行一次任務
->monthlyOn(4, '15:00');
每月 4 號的 15 點 執行一次任務
->quarterly();
每季度第一天 0 點執行一次任務
->yearly();
每年第一天 0 點執行一次任務
->timezone('America/New_York');
設置時區