-
创建一个任务类:
在终端中运行php aritsan make:command InsertFakeData
//名称自定义 -
打开生成的文件,目录在\App\Console\Commands\InsertFakeData.php,并修改handle方法如下:
<?php
namespace App\Console\Commands;
use Illuminate\Console\Command;
use Illuminate\Support\Facades\DB;
class InsertFakeData extends Command
{
/**
* The name and signature of the console command.
*
* @var string
*/
protected $signature = 'InsertFakeData';//自定义任务名称,手动执行用到
/**
* 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 int
*/
public function handle()
{
$totalRecords = 10000000;//总记录数
$chunkSize = 1000;//每次插入的记录数
DB::beginTransaction();
try{
for($i = 0;$i<$totalRecords;$i += $chunkSize){
$users = [];
for($j = 0 ;$j<$chunkSize;$j++){
$users[] = [
'name'=>'user'.($i+$j+1),
'sex'=>'男',
'age'=> 18,
'email'=>'user'($i+$j+1).'@wxample.com',
'phone'=>'13800000000',
'address'=>'中国大陆',
];
}
DB::table('user')->insert($users);
$this->info('Inserted'.$chunkSize.'fake users'.date("Y-m-d H:i:s"));
}
DB::commit();
$this->info('All fake users inserted successfully!');
}catch(\Exception $e){
DB::rollBack();
$this->error('Failed to insert fake users:'.$e->getMessage());
}
}
}
- 配置计划任务:在 Laravel 的计划任务文件 App\Console\Kernel.php的 schedule方法中,配置一个定时运行关闭订单任务的计划任务。具体如下:
protected function schedule(Schedule $schedule)
{
// $schedule->command('inspire')->hourly();
$schedule->command('InsertFakeData')->daily();//每天凌晨零点运行任务
}
更多时间配置可以去官方手册看 https://learnku.com/docs/laravel/8.x/scheduling/9399#scheduling-artisan-commands
- 注册命令:在 App\Console\Kernel.php 的 commands 方法中,注册一个新的命令,用于启动关闭订单任务。
protected $commands = [
Commands\CloseOrders::class,
];
- 执行任务计划,有两种方式:
手动执行命令php aritsan InsertFakeData
自动执行命令php aritsan schedule:run
注: InsertFakeData要和$signature属性设置的一致,要不然会报一个 Command “InsetFakeData”
is not defined. 的错误。