Cover of the book Symfony 5: The Fast Track

Symfony 5: The Fast Track is the best book to learn modern Symfony development, from zero to production. +300 pages showcasing Symfony with Docker, APIs, queues & async tasks, Webpack, SPAs, etc.


You are browsing the documentation for Symfony 5.0 which is not maintained anymore.

Consider upgrading your projects to Symfony 5.2.

Prevent Multiple Executions of a Console Command

5.0 version

Prevent Multiple Executions of a Console Command

A simple but effective way to prevent multiple executions of the same command in a single server is to use locks. The Lock component provides multiple classes to create locks based on the filesystem (FlockStore), shared memory (SemaphoreStore) and even databases and Redis servers.

In addition, the Console component provides a PHP trait called LockableTrait that adds two convenient methods to lock and release commands:

// ...
use Symfony\Component\Console\Command\Command;
use Symfony\Component\Console\Command\LockableTrait;
use Symfony\Component\Console\Input\InputInterface;
use Symfony\Component\Console\Output\OutputInterface;

class UpdateContentsCommand extends Command
    use LockableTrait;

    // ...

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

            return 0;

        // If you prefer to wait until the lock is released, use this:
        // $this->lock(null, true);

        // ...

        // if not released explicitly, Symfony releases the lock
        // automatically when the execution of the command ends

This work, including the code samples, is licensed under a Creative Commons BY-SA 3.0 license.