1、使用命令创建任务
php artisan make:command Points
2、提示创建成功后,会在项目app\Console\Commands目录下面生成Points.php文件
<?php
namespace App\Console\Commands;
use Illuminate\Console\Command;
use Illuminate\Support\Facades\DB;
class Points extends Command
{
/**
* The name and signature of the console command.
*
* @var string
*/
protected $signature = '任务名称';
/**
* 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()
{
//执行任务逻辑
}
}
3、然后编辑app\Console\目录下Kernel.php
<?php
namespace App\Console;
use App\Console\Commands\Points;
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 = [
Points::class //这里添加任务类
];
/**
* Define the application's command schedule.
*
* @param \Illuminate\Console\Scheduling\Schedule $schedule
* @return void
*/
protected function schedule(Schedule $schedule)
{
$schedule->command('give_points')
->everyMinute() //每分钟执行一次
}
/**
* Register the commands for the application.
*
* @return void
*
*/
protected function commands()
{
$this->load(__DIR__.'/Commands');
require base_path('routes/console.php');
}
}
4、开启lavavel任务调度器(重点)
crontab -e 添加以下代码
* * * * * php /project path/artisan schedule:run >> /dev/null 2>&1
crontab -l 可查看添加的任务调度列表
该cron会每分钟调用一次 laravel 命令调度器,然后laravel 会自动评估你的调度任务并运行到期的任务
其中 project path 为实际项目地址