Prevent Running the Same Console Command Multiple Times

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.

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

  1. // ...
  2. use Symfony\Component\Console\Command\Command;
  3. use Symfony\Component\Console\Command\LockableTrait;
  4. use Symfony\Component\Console\Input\InputInterface;
  5. use Symfony\Component\Console\Output\OutputInterface;
  6. class UpdateContentsCommand extends Command
  7. {
  8. use LockableTrait;
  9. // ...
  10. protected function execute(InputInterface $input, OutputInterface $output): int
  11. {
  12. if (!$this->lock()) {
  13. $output->writeln('The command is already running in another process.');
  14. return 0;
  15. }
  16. // If you prefer to wait until the lock is released, use this:
  17. // $this->lock(null, true);
  18. // ...
  19. // if not released explicitly, Symfony releases the lock
  20. // automatically when the execution of the command ends
  21. $this->release();
  22. return 0;
  23. }
  24. }

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