跳到内容

防止多次运行相同的控制台命令

编辑此页

您可以使用 来防止同一命令在同一服务器上多次运行。 Lock 组件提供了多个类,用于基于文件系统 (FlockStore)、共享内存 (SemaphoreStore) 甚至数据库和 Redis 服务器创建锁。

此外,Console 组件提供了一个名为 LockableTrait 的 PHP trait,它添加了两个方便的方法来锁定和释放命令

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;
    }
}

如果 SemaphoreStore 可用,LockableTrait 将使用它,否则将默认使用 FlockStore。您可以通过使用您自己的锁工厂设置 $lockFactory 属性来覆盖此行为

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
// ...
use Symfony\Component\Console\Command\Command;
use Symfony\Component\Console\Command\LockableTrait;
use Symfony\Component\Lock\LockFactory;

class UpdateContentsCommand extends Command
{
    use LockableTrait;

    public function __construct(private LockFactory $lockFactory)
    {
    }

    // ...
}

7.1

$lockFactory 属性在 Symfony 7.1 中引入。

本作品,包括代码示例,根据 Creative Commons BY-SA 3.0 许可协议获得许可。
目录
    版本