[0034]ProcessとCommandを利用して複数同時に非同期処理

■construct

Lalavel10 PHP 8.2.9で動作確認済

App\Console\Commandsの作成などは飛ばします。既にTestAとTestBのCommandがある前提から進めます。

TestAはCronから起動し、条件が満たしている場合にTestBを非同期処理で複数実行します。TestBはパラメータで受け取った内容に沿って処理を実行します。

TestBは同時に処理し、全部のTestBが終わったらTestAで最後の処理をしてCloseとなります。

TestAから渡すパラメータは配列をJson形式でTestBに渡し、TestBは配列で受取るようにしました。

TestA.php

              
<?php
namespace App\Console\Commands;

use Illuminate\Console\Command;
use App\Common\BaseClass;
use Log;
use DB;
use Exception;
use Illuminate\Process\Pool;
use Illuminate\Support\Facades\Process;

class TestA extends Command
{
    protected $signature = 'testA';

    protected $description = 'testA closing';

    public function handle()
    {
        $tai = DB::table('online_get_set')->orderBy('import_date')->orderBy('import_cnt')->first();
        if($tai->file_get_flg == 2 && $tai->file_uset_flg == 0){
            //条件を満たす場合
            $paras =  ['import_date'=>$tai->import_date,'import_cnt'=>$tai->import_cnt];
            $paras_arr = json_encode($paras);
            //json_encodeした配列をuseで使えるようにセットし、コマンドのパラメータに渡す
            $pool = Process::pool(function (Pool $pool) use($paras_arr) {
                $pool->as('first')->timeout(3600)->path('/var/www/vhost/xxx/')->command('php artisan testB '.$paras_arr.' > /dev/null 2>&1');
                $pool->as('second')->timeout(3600)->path('/var/www/vhost/xxx/')->command('php artisan testB '.$paras_arr.' > /dev/null 2>&1');
                $pool->as('third')->timeout(3600)->path('/var/www/vhost/xxx/')->command('php artisan testB '.$paras_arr.' > /dev/null 2>&1');
            })->start(function (string $type, string $output, int $key) {

            });
            //ここまで実行済
            $results = $pool->wait();//全部終わるまで待つ
            //ここから全部終わった処理Start↓

        }else{
            //取込中のため End
        }
    }
}
    			
            

TestB.php

              
<?php
namespace App\Console\Commands;

use Illuminate\Console\Command;
use App\Common\BaseClass;
use Log;
use DB;
use Exception;

class TestB extends Command
{
	//パラメータは配列で受け取るので*をつけている
    protected $signature = 'testB {tai*}';

    protected $description = 'testB closing';

    public function handle()
    {
        try{
        //$taiはパラメータで取得した配列
            $tai = $this->argument('tai');
            foreach($tai as $val){
            	list($k,$v) = explode(":",$val);
            	echo $k."は".$v."です";
            }

        }catch(Exception $e){

        }

    }
}
    			
            

キューみたいに利用できるし、速度改善に今後も色々利用できそう♪