第一步:用PHP命令创建你想要执行的任务的文件,用 php artisan make:command 后面加上名称然后回车,看到successfully说明创建成功;
执行完成后在app/console/commands文件夹中就会看到创建的文件
第二步:点击文件名称,编辑文件写上需要执行的程序:
<?php
namespace App\Console\Commands;
use Illuminate\Console\Command;
use App\Service\Basket\BasketService;
class BasketOrderCommission extends Command
{
/**
* The name and signature of the console command.
*
* @var string
*/
protected $signature = 'BasketOrderCommission';
/**
* 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()
{
$res = BasketService::BasketOrderCommission();
echo json_encode($res,JSON_UNESCAPED_UNICODE);
}
}
第三步:将写好的任务在kernel文件中进行注册:
<?php
namespace App\Console;
use Illuminate\Console\Scheduling\Schedule;
use Illuminate\Foundation\Console\Kernel as ConsoleKernel;
use Illuminate\Support\Facades\Log;
use App\Service\Purchasing\PurchasingService;
class Kernel extends ConsoleKernel
{
/**
* The Artisan commands provided by your application.
*
* @var array
*/
protected $commands = [
Commands\Testcommand::class,
Commands\train::class,
Commands\test::class,
Commands\BasketOrderCommission::class,
];
/**
* Define the application's command schedule.
*
* @param \Illuminate\Console\Scheduling\Schedule $schedule
* @return void
*/
protected function schedule(Schedule $schedule)
{
Log::info('【开始执行定时任务】time:'.date('Y-m-d H:i:s'));
$schedule->command('BasketOrderCommission')->everyTenMinutes();
}
/**
* Register the Closure based commands for the application.
*
* @return void
*/
protected function commands()
{
require base_path('routes/console.php');
}
}
第四步:注册成功后,用PHP命令执行一下任务,看看能不能跑通:php artisan +任务名称,即可单独运行任务
第五步:执行没问题了,在crontab命令中加入定时任务执行命令:crontab -e 回车
编辑定时任务命令:
关于 >/dev/null 2>&1 的解释:
0表示键盘输入
1表示标准输出
2表示错误输出.
编辑好以后保存退出,查看crontab命令:crontab -l
最后,十分钟或者一分钟执行一次,看日志记录看看执行情况就好了。