RetryAcquireTrait.php 949 B

123456789101112131415161718192021222324252627282930313233343536373839404142
  1. <?php
  2. /**
  3. * @link http://www.yiiframework.com/
  4. * @copyright Copyright (c) 2008 Yii Software LLC
  5. * @license http://www.yiiframework.com/license/
  6. */
  7. namespace yii\mutex;
  8. use Closure;
  9. /**
  10. * Trait RetryAcquireTrait.
  11. *
  12. * @author Robert Korulczyk <robert@korulczyk.pl>
  13. * @internal
  14. * @since 2.0.16
  15. */
  16. trait RetryAcquireTrait
  17. {
  18. /**
  19. * @var int Number of milliseconds between each try in [[acquire()]] until specified timeout times out.
  20. * By default it is 50 milliseconds - it means that [[acquire()]] may try acquire lock up to 20 times per second.
  21. * @since 2.0.16
  22. */
  23. public $retryDelay = 50;
  24. private function retryAcquire($timeout, Closure $callback)
  25. {
  26. $start = microtime(true);
  27. do {
  28. if ($callback()) {
  29. return true;
  30. }
  31. usleep($this->retryDelay * 1000);
  32. } while (microtime(true) - $start < $timeout);
  33. return false;
  34. }
  35. }