Skip to content

Instantly share code, notes, and snippets.

@ismail1432
Created October 22, 2023 08:12
Show Gist options
  • Save ismail1432/23189d77ad56276592cb0fd62c19679b to your computer and use it in GitHub Desktop.
Save ismail1432/23189d77ad56276592cb0fd62c19679b to your computer and use it in GitHub Desktop.
<?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