自定义命令和任务
Laravel artisan 支持自定义命令和设置定时任务。
自定义命令
例子 自定义数据库清理命令
运行一下命令,创建FreshTablesMonthly命令
php artisan make:command FreshTablesMonthly
运行完后,发现已经创建app/Console/Commands/FreshTablesMonthly.php文件。
修改这个文件的handle()方法,在这个方法中调用,数据库刷新命令和填充数据命令。
<?php
namespace App\Console\Commands;
use Illuminate\Console\Command;
use App\Tools\Helper;
class FreshTablesMonthly extends Command
{
/**
* The name and signature of the console command.
*
* @var string
*/
protected $signature = 'maintain:freshTablesMonthly';
/**
* The console command description.
*
* @var string
*/
protected $description = 'drop tables, build tables and seed';
/**
* Create a new command instance.
*
* @return void
*/
public function __construct() {
parent::__construct();
}
/**
* Execute the console command.
*
* @return mixed
*/
public function handle() {
$runFreshTablesMonthlyBool = env( 'runFreshTablesMonthlyBool', false );
if( $runFreshTablesMonthlyBool == false ){
Helper::echoIt( __METHOD__, __LINE__, [ 'env.runFreshTablesMonthlyBool == false' ] );
return false;
}
Helper::echoIt( __METHOD__, __LINE__, [ 'runFreshTablesMonthlyBool start:' ] );
\Artisan::call('migrate:fresh');
Helper::echoIt( __METHOD__, __LINE__, [ 'runFreshTablesMonthlyBool migrate:fresh done' ] );
\Artisan::call('db:seed');
Helper::echoIt( __METHOD__, __LINE__, [ 'runFreshTablesMonthlyBool db:seed done' ] );
Helper::echoIt( __METHOD__, __LINE__, [ 'runFreshTablesMonthlyBool done' ] );
}
}
另外,使用composer dump-autoload命令可以重新加载类
以上已经完成自定义命令,可以像其他Artisan一样使用命令行调用
设置定时任务
设置Crontab
$ serevice cron start
$ crontab -e
##加入以下定时任务,每分钟调用laravel总任务
* * * * * cd /path-to-your-project && php artisan schedule:run >> /dev/null 2>&1
注册定时任务执行自定义命令
打开app/Console/Kernel.php文件,修改$commands成员变量和成员方法schedule()。
如下注册了App\Console\Commands\FreshTablesMonthly命令,并且每月1号00点1分执行一次。
<?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\FreshTablesMonthly',
];
/**
* Define the application's command schedule.
*
* @param \Illuminate\Console\Scheduling\Schedule $schedule
* @return void
*/
protected function schedule(Schedule $schedule) {
// $schedule->command('inspire')->hourly();
$schedule->command( 'maintain:freshTablesMonthly' )->cron('1 0 1 * *')->withoutOverlapping();
}
/**
* Register the commands for the application.
*
* @return void
*/
protected function commands()
{
$this->load(__DIR__.'/Commands');
require base_path('routes/console.php');
}
}