diff --git a/README.md b/README.md index dd0f5d8..353769f 100644 --- a/README.md +++ b/README.md @@ -163,6 +163,7 @@ Below shows the redis mutex demo: 'components' => [ 'mutex' => [ 'class' => 'yii\redis\Mutex', + 'autoRelease' => false, // You should disable autoRelease here 'redis' => [ 'hostname' => 'localhost', 'port' => 6379, diff --git a/src/CallbackEvent.php b/src/CallbackEvent.php index a11b3f7..b960153 100644 --- a/src/CallbackEvent.php +++ b/src/CallbackEvent.php @@ -69,10 +69,11 @@ public function run(Application $app) /** * Do not allow the event to overlap each other. * + * @param int $expiresAt * @return $this * @throws InvalidParamException */ - public function withoutOverlapping() + public function withoutOverlapping($expiresAt = 1440) { if (empty($this->_description)) { throw new InvalidParamException( @@ -80,7 +81,7 @@ public function withoutOverlapping() ); } - return parent::withoutOverlapping(); + return parent::withoutOverlapping($expiresAt); } /** diff --git a/src/Event.php b/src/Event.php index 3dfec6a..aa372cb 100644 --- a/src/Event.php +++ b/src/Event.php @@ -11,7 +11,7 @@ use yii\base\InvalidConfigException; use yii\mail\MailerInterface; use yii\mutex\Mutex; -use yii\mutex\FileMutex; +use yii\redis\Mutex as RedisMutex; /** * Class Event @@ -508,10 +508,14 @@ public function user($user) /** * Do not allow the event to overlap each other. * + * @param int $expiresAt * @return $this */ - public function withoutOverlapping() + public function withoutOverlapping($expiresAt = 1440) { + if ($this->_mutex instanceof RedisMutex) { + $this->_mutex->expire = $expiresAt * 60; + } return $this->then(function() { $this->_mutex->release($this->mutexName()); })->skip(function() { @@ -526,11 +530,15 @@ public function withoutOverlapping() */ public function onOneServer() { - if ($this->_mutex instanceof FileMutex) { - throw new InvalidConfigException('You must config mutex in the application component, except the FileMutex.'); + if (!$this->_mutex instanceof RedisMutex) { + throw new InvalidConfigException('You must config redis mutex in the application component.'); } - - return $this->withoutOverlapping(); + $time = new \DateTime('now'); + $name = $this->mutexName() . $time->format('Hi'); + $this->_mutex->expire = 3600; + return $this->skip(function() use ($name) { + return !$this->_mutex->acquire($name); + }); } /**