You are browsing the Symfony 4 documentation, which changes significantly from Symfony 3.x. If your app doesn't use Symfony 4 yet, browse the Symfony 3.4 documentation.

Prevent Multiple Executions of a Console Command

4.2 version
Maintained Unmaintained

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:

 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
// ...
use Symfony\Component\Console\Command\LockableTrait;

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->release();
    }
}

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