我升级到 Symfony 3.4.* 以利用新的锁组件。然而,它似乎在开发中工作,但在生产中总是获得锁。这是我的代码:
BaseCommandWrapper:
<?php
namespace CoreBundle\Command;
ini_set('max_execution_time', 3600);
use Symfony\Bundle\FrameworkBundle\Command\ContainerAwareCommand;
use Symfony\Component\Lock\Factory;
use Symfony\Component\Lock\Store\SemaphoreStore;
use Symfony\Component\Console\Command\LockableTrait;
class BaseCommandWrapper extends ContainerAwareCommand {
use LockableTrait;
function start($commandName) {
$this->commandName = $commandName;
$store = new SemaphoreStore();
$factory = new Factory($store);
$this->lock = $factory->createLock($this->commandName);
if (!$this->lock->acquire()) {
echo 'This command is already running in another process.' . PHP_EOL;
return false;
}
echo "Lock aquired" . PHP_EOL;
return $this->lock;
}
function stop() {
echo "Releasing lock" . PHP_EOL;
$this->lock->release();
}
}
?>
命令本身:
class SomeCommand extends BaseCommandWrapper
{
protected function configure()
{
$this
->setName('processSomeCommand')
->setDescription('Process Some Command')
;
}
protected function execute(InputInterface $input, OutputInterface $output)
{
if ($this->start($this->getName()) === false) {
return 0;
}
sleep(60);
$this->stop();
}
所有命令都由 cron 触发,在这种情况下每秒触发一次。