版权声明:本文为博主原创文章,未经博主允许不得转载。 https://blog.csdn.net/zuimei_forver/article/details/82317161
下面介绍一个Laravel任务调度使用实例,至于相关的方法请参考:http://laravelacademy.org/post/8484.html
1. make:command 生成任务
php artisan make:command MigrateData
执行上述命令后,会在Console目录新建一个Commands目录,里面有个MigrateData.php文件
2. 编写任务
在MigrateData.php的handle方法中编写要处理的逻辑,下面附上内容
<?php
namespace App\Console\Commands;
use Illuminate\Console\Command;
class MigrateData extends Command
{
/**
* The name and signature of the console command.
*
* @var string
*/
protected $signature = 'migrateData';
/**
* The console command description.
*
* @var string
*/
protected $description = 'migrate data';
/**
* Create a new command instance.
*
* @return void
*/
public function __construct()
{
parent::__construct();
}
/**
* Execute the console command.
*
* @return mixed
*/
public function handle()
{
//仅仅输出一个日志,看是否成功
file_put_contents('/home/www/test.log', date("Y-m-d H:i:s") . PHP_EOL, FILE_APPEND);
}
}
3. 修改Console的Kernel.php文件
<?php
namespace App\Console;
use App\Console\Commands\MigrateData;
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\MigrateData::class,
];
/**
* 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(MigrateData::class)->everyMinute();
//或者 migrateData为类MigrateData中的$signature
$schedule->command("migrateData")->everyMinute();
}
/**
* Register the commands for the application.
*
* @return void
*/
protected function commands()
{
$this->load(__DIR__.'/Commands');
require base_path('routes/console.php');
}
}
4. 设置cron任务
在linux下crontab -e 设置定时任务
/usr/local/php/bin/php /home/www/project/artisan schedule:run >> /dev/null 2>&1
5. 备注
如果执行不成功,可以直接执行/usr/local/php/bin/php /home/www/project/artisan schedule:run >> /dev/null 2>&1
,看是否调度成功。如果没有,证明代码有问题。
如果需要传递参数,可以进行如下设置:
① 命令类的修改
protected $signature = 'migrateData param1';
② kernel.php调用修改
$schedule->command("migrateData 1")->everyMinute();
③ 命令类中获取参数
public function handle()
{
$param1 = $this->argument('param1');
}