1.创建一个自定义的Command
PHP artisan make:command tests
2.然后会生成tests.php文件(app/Console/Commands/tests.php)上面有我写的说明
<?php
namespace App\Console\Commands;
use Illuminate\Console\Command;
use Illuminate\Support\Facades\DB;
class Tests extends Command
{
/**
* The name and signature of the console command.
*
* @var string
*/
protected $signature = '自定义名称';
/**
* 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()
{
//运行代码的逻辑
}
}
3.然后修改kernel.php (app/Console/Kernel.php)
将之前创建的tests.php 文件里 你自己定义的名称 对应上Kernel.php里的名称
<?php
namespace App\Console;
use App\Console\Commands\test;
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 = [
Test::class
];
/**
* Define the application's command schedule.
*
* @param \Illuminate\Console\Scheduling\Schedule $schedule
* @return void
*/
protected function schedule(Schedule $schedule)
{
$schedule->command('自定义名称')->everyMinute()->withoutOverlapping();
}
/**
* Register the commands for the application.
*
* @return void
*/
protected function commands()
{
$this->load(__DIR__.'/Commands');
require base_path('routes/console.php');
}
}
4.可以自定义定时时间 这是定义时间函数
->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'); 设置时区
->weekdays(); 限制任务在工作日执行
->weekends(); 限制任务在周末执行
->sundays(); 限制任务在周日执行
->mondays(); 限制任务在周一执行
->tuesdays(); 限制任务在周二执行
->wednesdays(); 限制任务在周三执行
->thursdays(); 限制任务在周四执行
->fridays(); 限制任务在周五执行
->saturdays(); 限制任务在周六执行
->between($start, $end); 限制任务在 $start 和 $end 区间执行->hourly()->between('7:00', '22:00');
->when(Closure); 限制任务在闭包返回为真时执行
->environments($env); 限制任务在特定环境执行
->withoutOverlapping(); 避免任务重复执行
5.都设置好后就可以执行定时任务了
(1)手动执行
php artisan command:tests