Laravel篇:使用任务调度器来处理插入大量数据的方法

  1. 创建一个任务类:
    在终端中运行php aritsan make:command InsertFakeData //名称自定义

  2. 打开生成的文件,目录在\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());
        }
    }
}

  1. 配置计划任务:在 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

  1. 注册命令:在 App\Console\Kernel.php 的 commands 方法中,注册一个新的命令,用于启动关闭订单任务。
 protected $commands = [
     Commands\CloseOrders::class,
 ];
  1. 执行任务计划,有两种方式:
    手动执行命令 php aritsan InsertFakeData
    自动执行命令 php aritsan schedule:run

注: InsertFakeData要和$signature属性设置的一致,要不然会报一个 Command “InsetFakeData”
is not defined. 的错误。

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 1
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论 1
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值