1.创建一个自定义的Command
PHP artisan make:command test
2.编辑test.php文件(app/Console/Commands/test.php)
<?php
namespace App\Console\Commands;
use Illuminate\Console\Command;
use Illuminate\Support\Facades\Log;
class test extends Command
{
/**
* The name and signature of the console command.
*
* @var string
*/
protected $signature = 'command: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 mixed
*/
public function handle()
{
Log::info(time().'测试定时任务');
}
}
3.修改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('command:test')->everyMinute()->withoutOverlapping();
}
/**
* Register the commands for the application.
*
* @return void
*/
protected function commands()
{
$this->load(__DIR__.'/Commands');
require base_path('routes/console.php');
}
}
调用频率和限制说明
->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(); 避免任务重复执行
4.执行定时任务
手动执行:php artisan command:test
服务器自动执行:
1.编辑定时任务:
crontab -e
2.php多版本可以将php改为版本的绝对路径,项目路径
* * * * * php /www/wwwroot/laravel/laravel/artisan schedule:run >> /dev/null 2>&1
其实这个打开这个文件编辑也是一样的:
3.查看定时任务
crontab -l
4.重启cron服务
CentOS7方法:
重启服务
systemctl restart crond.service
CentOS6方法:
重启服务
service crond restart
5.结果
[2022-06-13 07:34:01] local.INFO: 1655105641测试定时任务
[2022-06-13 07:35:01] local.INFO: 1655105701测试定时任务
[2022-06-13 07:36:02] local.INFO: 1655105762测试定时任务
[2022-06-13 07:37:01] local.INFO: 1655105821测试定时任务