/** * Throttle * * @param string $key - A unique key for what we're throttling * @param int $limit - How many are allowed * @param int $milliseconds - In this many milliseconds * @return void */ public function throttle($key, $limit, $milliseconds) { /** * Try do our waiting without a lock, so may sneak through because of * this... */ $wait = $this->getEstimate($key, $limit, $milliseconds); if ($wait > 0) { usleep($wait * 1000); } $key = $this->getStorageKey($key, $limit, $milliseconds); $this->storage->lock($key); $count = $this->storage->get($key); $count++; $this->storage->set($key, $count); $this->storage->unlock($key); return $wait; }
/** * Throttle * * @param string $key - A unique key for what we're throttling * @param int $limit - How many are allowed * @param int $milliseconds - In this many milliseconds * @return void */ public function throttle($key, $limit, $milliseconds) { /** * Try and do our waiting without a lock */ $key = $this->getStorageKey($key, $limit, $milliseconds); $wait = 0; $newRatio = $this->getNewRatio($key, $limit, $milliseconds); if ($newRatio > $milliseconds) { $wait = ceil($newRatio - $milliseconds); } usleep($wait * 1000); /** * Lock, record and release */ $this->storage->lock($key); $newRatio = $this->getNewRatio($key, $limit, $milliseconds); $this->setLastRatio($key, $newRatio); $this->setLastRequest($key, microtime(1)); $this->storage->unlock($key); return $wait; }