Laravel自定义命令文件在目录:
app/Console/Commads
- 创建自定义命令文件:
php artisan make:command Test
-
protected $signature = ‘test:show’;
则此文件的自定义命令为test:show,可接受参数test:show {param},规定参数后参数必传 -
protected $description = ‘此处为命令描述’;
-
handle() 函数为命令执行内容
public function handle()
{
$this->info('开始');
//接收参数
$param = $this->argument('param');
$this->info($param);
$this->info('结束');
}
- 执行自定义命令
php artisan test:show 123
Laravel定时任务文件为
app/Console/Kernel.php
protected $commands 的数组内容为引用的自定义命令文件类
protected $commands = [
//使用上面创建的Test自定义命令类(可引用多个)
Test::class
];
schedule() 函数为定时任务执行函数
protected function schedule(Schedule $schedule)
{
//每五分钟执行一次
$schedule->command('test:show 123')->everyFiveMinutes();
}
具体调度方法时间表可参考:定时任务调度在 Laravel 中的实现
注:假设当前系统为Linux,需使用Linux的crontab -e命令来增加一条定时任务用来配合Laravel的定时任务;
如:每分钟检测一次当前是否有需要执行的定时任务
* * * * * php /path-to-your-project/artisan schedule:run >> /dev/null 2>&1