注意:laravel自带的定时任务最低1分钟执行一次,必须使用shell脚本
1:首先进入到laravel/app/console 目录下,Console 目录包含应用所有自定义的 Artisan 命令,这些命令类可以使用 make:command 命令生成。该目录下还有 Console/Kernel 类,在这里可以注册自定义的 Artisan 命令以及定义调度任务。
php artisan make:command Charge
2:创建完之后,打开console目录下的commands目录,我们会发现里面已经有了一个文件
<?php
/*
* 定时任务---更新预约状态
*/
namespace App\Console\Commands;
use App\Models\Test;
use Illuminate\Console\Command;
class Charge extends Command
{
/**
* 此处代表laravel自动生成的名称,下面执行的时候能用到
* The name and signature of the console command.
*
* @var string
*/
protected $signature = 'order_charge';
/**
* The console command description.
*
* @var string
*/
protected $description = 'order_charge';
/**
* Create a new command instance.
*
* @return void
*/
public function __construct()
{
parent::__construct();
}
/**
* Execute the console command.
*
* @return mixed
*/
public function handle()
{
//具体业务操作
\Log::info('预约订单更新状态');
$ini['user_id'] = 1;
$ini['add_time'] = date("Y-m-d H:i:s",time());
Test::insert($ini);
}
}
3、定时命令创建好之后,我们需要修改kernel.php文件
<?php
namespace App\Console;
use App\Console\Commands\Charge;
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 = [
//定时任务的名称
Charge::class
];
/**
*1、这个方法按照自己的需求,确定定时方法的执行顺序
* Define the application's command schedule.
* @param \Illuminate\Console\Scheduling\Schedule $schedule
* @return void
*/
protected function schedule(Schedule $schedule)
{
$schedule->command('order_charge')->everyMinute();
}
/**
* Register the commands for the application.
*
* @return void
*/
protected function commands()
{
$this->load(__DIR__.'/Commands');
require base_path('routes/console.php');
}
}
4:执行定时任务
a)在/root/shell/文件夹里面建个脚本文件 charge.sh
#!/bin/bash
step=5 #间隔的秒数
for (( i = 0; i < 60; i=(i+step) )); do
/usr/bin/php /www/wwwroot/ychongdian/artisan schedule:run >> /home/shell/log/charge.log 2>&1
sleep $step
done
exit 0
第一个参数是php所在的位置 可以用 which php
第二个位置是项目的目录文件夹
b)脚本赋予执行的权限 chmod +x charge.sh
c)crontab -e 输入以下语句,然后:wq 保存退出。
* * * * * /root/shell/charge.sh
至此laravael定时任务完成