|
| 1 | +Prevent Multiple Executions of a Console Command |
| 2 | +================================================ |
| 3 | + |
| 4 | +A simple but effective way to prevent multiple executions of the same command in |
| 5 | +a single server is to use **file locks**. The Filesystem component provides a |
| 6 | +:doc:`LockHandler </components/filesystem/lock_handler>` class that eases the |
| 7 | +creation and release of these locks:: |
| 8 | + |
| 9 | + // ... |
| 10 | + use Symfony\Component\Filesystem\LockHandler; |
| 11 | + |
| 12 | + class UpdateContentsCommand extends Command |
| 13 | + { |
| 14 | + // ... |
| 15 | + |
| 16 | + protected function execute(InputInterface $input, OutputInterface $output) |
| 17 | + { |
| 18 | + // create the lock (tip: use the command name as the lock name |
| 19 | + // to ensure its uniqueness) |
| 20 | + $lock = new LockHandler('update:contents'); |
| 21 | + if (!$lock->lock()) { |
| 22 | + $output->writeln('The command is already running in another process.'); |
| 23 | + |
| 24 | + return 0; |
| 25 | + } |
| 26 | + |
| 27 | + // ... |
| 28 | + |
| 29 | + // if not released explicitly, Symfony releases the lock |
| 30 | + // automatically when the execution of the command ends |
| 31 | + $lock->release(); |
| 32 | + } |
| 33 | + } |
| 34 | + |
| 35 | +The Console component provides a PHP trait called ``LockableTrait`` that adds |
| 36 | +two convenient methods to lock and release commands:: |
| 37 | + |
| 38 | + // ... |
| 39 | + use Symfony\Component\Console\Command\LockableTrait; |
| 40 | + |
| 41 | + class UpdateContentsCommand extends Command |
| 42 | + { |
| 43 | + use LockableTrait; |
| 44 | + |
| 45 | + // ... |
| 46 | + |
| 47 | + protected function execute(InputInterface $input, OutputInterface $output) |
| 48 | + { |
| 49 | + if (!$this->lock()) { |
| 50 | + $output->writeln('The command is already running in another process.'); |
| 51 | + |
| 52 | + return 0; |
| 53 | + } |
| 54 | + |
| 55 | + // If you prefer to wait until the lock is released, use this: |
| 56 | + // $this->lock(true); |
| 57 | + |
| 58 | + // ... |
| 59 | + |
| 60 | + // if not released explicitly, Symfony releases the lock |
| 61 | + // automatically when the execution of the command ends |
| 62 | + $this->release(); |
| 63 | + } |
| 64 | + } |
0 commit comments