Prevent to Run Console Command Multiple Times in Symfony 7

Prevent to Run Console Command Multiple Times in Symfony 7

Symfony Console component is a powerful tool for building command line applications in PHP. However, there are scenarios where you want to ensure that a particular console command is not executed multiple times concurrently. This is especially crucial in scenarios where a command performs critical operations or alters the state of the application. This tutorial shows how to prevent to run console command multiple times in Symfony 7.

Symfony provides a Lock component that can be utilized to prevent concurrent execution of commands. The Console component provides a PHP trait called LockableTrait which is based on the Lock component.

By acquiring a lock before the command starts and releasing it when the command finishes, we can ensure that only one instance of the command is running at a time.

<?php

namespace App\Command;

use Symfony\Component\Console\Attribute\AsCommand;
use Symfony\Component\Console\Command\Command;
use Symfony\Component\Console\Command\LockableTrait;
use Symfony\Component\Console\Input\InputInterface;
use Symfony\Component\Console\Output\OutputInterface;

#[AsCommand(name: 'app:test')]
class TestCommand extends Command
{
    use LockableTrait;

    protected function execute(InputInterface $input, OutputInterface $output): int
    {
        if (!$this->lock()) {
            $output->writeln('The command is already running within a different process.');

            return Command::SUCCESS;
        }

        sleep(5);
        $output->writeln('Long-running task done.');

        return Command::SUCCESS;
    }
}

Please be aware that Symfony automatically releases the lock upon completion of the command execution.

Leave a Comment

Cancel reply

Your email address will not be published.