Skip to content

Commit 0e7abbb

Browse files
committed
feature #6953 Documented the Lockable Trait (javiereguiluz)
This PR was squashed before being merged into the master branch (closes #6953). Discussion ---------- Documented the Lockable Trait This fixes #6678 Commits ------- b0495e0 Documented the Lockable Trait
2 parents 6a90c82 + b0495e0 commit 0e7abbb

File tree

1 file changed

+38
-0
lines changed

1 file changed

+38
-0
lines changed

console/lockable_trait.rst

Lines changed: 38 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,38 @@
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+
In addition, the Console component provides a PHP trait called ``LockableTrait``
10+
that adds two convenient methods to lock and release commands::
11+
12+
// ...
13+
use Symfony\Component\Console\Command\LockableTrait;
14+
15+
class UpdateContentsCommand extends Command
16+
{
17+
use LockableTrait;
18+
19+
// ...
20+
21+
protected function execute(InputInterface $input, OutputInterface $output)
22+
{
23+
if (!$this->lock()) {
24+
$output->writeln('The command is already running in another process.');
25+
26+
return 0;
27+
}
28+
29+
// If you prefer to wait until the lock is released, use this:
30+
// $this->lock(true);
31+
32+
// ...
33+
34+
// if not released explicitly, Symfony releases the lock
35+
// automatically when the execution of the command ends
36+
$this->release();
37+
}
38+
}

0 commit comments

Comments
 (0)