dominicwatts / consolelock
锁定控制台命令
1.0.0
2020-05-31 22:33 UTC
Requires
- php: ~5.6.0||~7.0.0||~7.1.0||~7.2.0||~7.3.0
- magento/framework: *
- symfony/lock: *
This package is auto-updated.
Last update: 2024-08-29 05:13:06 UTC
README
使用Symfony锁定组件和magento控制台命令进行实验。锁定控制台命令和cron进程,以防止重叠、重复进程或资源过载。
https://symfony.com.cn/doc/current/components/lock.html#flockstore
安装
composer require symfony/lock
使用方法
FlockStore
https://symfony.com.cn/doc/current/components/lock.html#lock-store-flock
示例控制台命令
[...] use Magento\Framework\Filesystem\DirectoryList; use Symfony\Component\Lock\LockFactory; use Symfony\Component\Lock\Store\FlockStore; [...]
/** * Console Test script * @param \Magento\Framework\Filesystem\DirectoryList $dir */ public function __construct( DirectoryList $dir ) { $this->dir = $dir; parent::__construct(); }
$store = new FlockStore($this->dir->getPath('var')); $factory = new LockFactory($store);
示例 1
$lock = $factory->createLock('lock-name'); if ($lock->acquire()) { // do stuff $lock->release(); } else { // cannot get lock }
示例 2
$lock = $factory->createLock('lock-name', 30); $lock->acquire(); try { // perform a job during less than 30 seconds } catch (\Exception $e) { // whoops - error } finally { $lock->release(); }
示例控制台脚本
<?php declare(strict_types=1); namespace Xigen\ConsoleLock\Console\Command; use Magento\Framework\App\Area; use Magento\Framework\App\State; use Magento\Framework\Filesystem\DirectoryList; use Symfony\Component\Console\Command\Command; use Symfony\Component\Console\Input\InputInterface; use Symfony\Component\Console\Output\OutputInterface; use Symfony\Component\Lock\LockFactory; use Symfony\Component\Lock\Store\FlockStore; class Run extends Command { /** * @var DirectoryList */ protected $dir; /** * @var State */ private $state; /** * Console Test script * @param \Magento\Framework\Filesystem\DirectoryList $dir * @param \Magento\Framework\App\State $state */ public function __construct( DirectoryList $dir, State $state ) { $this->dir = $dir; $this->state = $state; parent::__construct(); } /** * {@inheritdoc} */ protected function execute( InputInterface $input, OutputInterface $output ) { $this->state->setAreaCode(Area::AREA_GLOBAL); $output->writeln('<info>Start</info>'); $store = new FlockStore($this->dir->getPath('var')); $factory = new LockFactory($store); $output->writeln('<info>Creating lock</info>'); $lock = $factory->createLock('test-console-run'); if ($lock->acquire()) { $output->writeln('<warning>Releasing lock in 60 secs</warning>'); // fake long running process sleep(60); $output->writeln('<info>Releasing lock</info>'); $lock->release(); } else { $output->writeln('<error>Cannot aquire lock</error>'); } $output->writeln('<info>Finish</info>'); } /** * {@inheritdoc} */ protected function configure() { $this->setName("xigen:consolelock:run"); $this->setDescription("Test lock"); parent::configure(); } }