方法一:
- 打开laravel,输入命令
php artisan make:command Test
- 2.修改两处位置
一处为名称,一处为Handel方法的代码段
<?php
namespace App\Console\Commands;
use Illuminate\Support\Facades\DB;
use Illuminate\Console\Command;
class Test extends Command
{
/**
* The name and signature of the console command.
*
* @var string
*/
//name修改成自己要用的名称,之后方便,区分并调用
protected $signature = 'command:name';
/**
* The console command description.
*
* @var string
*/
//对定时任务的描述
protected $description = 'Command description';
/**
* Create a new command instance.
*
* @return void
*/
//这个是laravel自带的构造方法。初始状态下是空的
public function __construct()
{
parent::__construct();
}
/**
* Execute the console command.
*
* @return mixed
*/
public function handle()
{
/*
* 可以用模型
* 放自己要定时做什么的代码段
* */
//更新
DB::table('order')->where('status',1)->update(['hot_status'=>2]);
}
}
3.修改app/console/ Kernel.php 文件,主要是定义命令的调度时间,定义命令的执行先后顺序等4
<?php
namespace App\Console;
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 = [
//一定要引入我们新创建的类,可以引入多个
\App\Console\Commands\Test::class
];
/**
* Define the application's command schedule.
*
* @param \Illuminate\Console\Scheduling\Schedule $schedule
* @return void
*/
protected function schedule(Schedule $schedule)
{
// command('command:name')这个name值跟之前那个command里的要统一,告诉它我注册哪个
$schedule->command('command:name')->everyMinute();
}
/**
* Register the commands for the application.
*
* @return void
*/
//这个部分是laravel自动生成的,引入我们生成的命令文件,不需要动
protected function commands()
{
$this->load(__DIR__.'/Commands');
require base_path('routes/console.php');
}
}
4.上传到宝塔前的检测,要检测自己的代码是否有问题
php artisan command:name
php artisan schedule:run
5.有效果就去上传到宝塔。如果有数据库操作,就要修改宝塔上自己的账号,密码,数据库,要和宝塔上的数据库统一。本地代码可以不用管了。
6.linux准备执行我们的定时:
crontab -e
* * * * * /usr/bin/php /path-to-your-project/artisan command:name >> /dev/null 2>&1
7.退出定时任务,在自己的宝塔上的项目上测试是否成功
php artisan schedule:run