Prevent Running the Same Console Command Multiple Times

You can use locks to prevent the same command from running multiple times on the same server. The Lock component provides multiple classes to create locks based on the filesystem (FlockStore), shared memory (SemaphoreStore) and even databases and Redis servers.

ロックを使用して、同じコマンドが同じサーバーで複数回実行されるのを防ぐことができます。 Lock コンポーネントは、ファイルシステム (FlockStore)、共有メモリ (SemaphoreStore)、さらにはデータベースや Redis サーバーに基づいてロックを作成するための複数のクラスを提供します。

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

さらに、コンソール コンポーネントは、LockableTrait と呼ばれる PHP 特性を提供します。これは、コマンドをロックおよび解放するための 2 つの便利なメソッドを追加します。
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
28
29
30
31
32
// ...
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): int
    {
        if (!$this->lock()) {
            $output->writeln('The command is already running in another process.');

            return Command::SUCCESS;
        }

        // 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();

        return Command::SUCCESS;
    }
}