Have issue while delaying with sleep

Viewed 71


I have users that are related to some accounts in another system.
I need users that are related to single account to have delay between queries to the system while they are working/opening windows in browser.
I am using redis to keep timeouts between queries and my app is written on yii2 framework.

For example:
I have two users that are related to single account and delay should be 5 seconds. So the flow should be so: if the first user opens 4 windows at the same time the last window should have delay 20secs and if the second user opens 1 window at the same time he should have delay 25secs.

Here is delay calculating code:

// <!-- Calculating timeout
  /** @var Connection $redis */
  $redis = Yii::$app->redis;
  $redisTimeoutKey = "account:" . $user->account->id;

  $delay = 5;
  $timeout = $redis->get($redisTimeoutKey);
  $toSleep = $timeout - time();
  if ($toSleep > 0) {
    $redis->set($redisTimeoutKey, $timeout + $delay);
    sleep($toSleep);
  } else {
    $redis->set($redisTimeoutKey, time() + $delay);
  }
  // -->
  // request to the system here

I have correct calculating for single user but the second user does not see the last delay calculating. What is exactly happening here?

0 Answers
Related