Skip to content

Instantly share code, notes, and snippets.

@vuthaihoc
Created August 2, 2023 04:59
Show Gist options
  • Save vuthaihoc/427f79bafa3d654aca579963fdb3eb14 to your computer and use it in GitHub Desktop.
Save vuthaihoc/427f79bafa3d654aca579963fdb3eb14 to your computer and use it in GitHub Desktop.
Call artisan command with timeout
<?php
namespace App\Console\Commands;
use Illuminate\Support\Facades\Process;
trait AdvancedCommandCallTrait
{
protected function advancedCallCommand($command, $parameters = [], $timeout = 300, $idleTimeout = 120) : void
{
$command = ["php", "artisan", $command];
foreach ($parameters as $k => $v){
if(is_array($v)){
foreach ($v as $_v){
$command[] = $k . "=" . $_v;
}
}elseif ($v === true){
$command[] = $k;
}else{
$command[] = $k . "=" . $v;
}
}
Process::timeout($timeout)
->path(base_path())
->idleTimeout($idleTimeout)
->run($command, function (string $type, string $output) {
$output = rtrim($output, "\n");
if($type == 'stderr'){
$this->error($output);
}else{
$this->info($output);
}
});
}
}
<?php
namespace App\Console\Commands;
use App\Console\Commands\AdvancedCommandCallTrait;
use Illuminate\Support\Facades\Process;
class TestSth extends Command
{
/**
* The name and signature of the console command.
*
* @var string
*/
protected $signature = 'test:sth';
/**
* The console command description.
*
* @var string
*/
protected $description = 'Command description';
use AdvancedCommandCallTrait;
/**
* Execute the console command.
*
* @return int
*/
public function handle()
{
$this->advancedCallCommand(
'task:convert',
['all' =>true, '-f' => true,'-vvv' => true,'--id' => '885695835560050689'],
100,
50,
);
return Command::SUCCESS;
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment