-
-
Save ismail1432/23189d77ad56276592cb0fd62c19679b to your computer and use it in GitHub Desktop.
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
<?php | |
namespace App\Command; | |
use Symfony\Component\Console\Command\Command; | |
use Symfony\Component\Console\ConsoleEvents; | |
use Symfony\Component\Console\Event\ConsoleErrorEvent; | |
use Symfony\Component\Console\Style\SymfonyStyle; | |
use Symfony\Component\EventDispatcher\Attribute\AsEventListener; | |
#[AsEventListener(ConsoleEvents::ERROR, 'retry')] | |
class RetryOnConsoleErrorListener | |
{ | |
public function retry(ConsoleErrorEvent $event) | |
{ | |
$command = $event->getCommand(); | |
$input = $event->getInput(); | |
$output = $event->getOutput(); | |
// Get the retry configuration. | |
$retries = $input->getOption('retry'); | |
$delay = $input->getOption('delay'); | |
$multiplier = $input->getOption('multiplier'); | |
$io = new SymfonyStyle($input, $output); | |
$i = 0; | |
while($i !== $retries) { | |
try { | |
$io->warning(sprintf('Command failed %s, let\'s retry 🚀 after waiting %s milliseconds', str_repeat("😭",$i+1), $delay)); | |
// Wait the given milliseconds delay | |
usleep($delay * 1000); | |
// Debug purpose | |
dump(time()); | |
$io->warning(sprintf('Retry %s', str_repeat("🔥",$i+1))); | |
// Re-run the command | |
$exitCode = $command->run($input, $output); | |
// Exit in case of success | |
if ($exitCode === Command::SUCCESS) { | |
break; | |
} | |
} catch (\Throwable $e) { | |
// Exit in case of max retries reached | |
if ($i === $retries) { | |
throw $e; | |
} | |
} finally { | |
// Increase retries and delay | |
++$i; | |
$delay *= $multiplier; | |
} | |
} | |
} | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment