Maintain maximum 2 calls per second to the API

@see https://help.shopify.com/api/guides/api-call-limit

@param bool $firstCallWait Whether to maintain the wait time even if it is the first API call
434259
public static function checkApiCallLimit($firstCallWait = false)
    {
        $timeToWait = 0;
        if (static::$microtimeOfLastApiCall == null) {
            if ($firstCallWait) {
                $timeToWait = static::$timeAllowedForEachApiCall;
            }
        } else {
            $now = microtime(true);
            $timeSinceLastCall = $now - static::$microtimeOfLastApiCall;
            //Ensure 2 API calls per second
            if($timeSinceLastCall < static::$timeAllowedForEachApiCall) {
                $timeToWait = static::$timeAllowedForEachApiCall - $timeSinceLastCall;
            }
        }

        if ($timeToWait) {
            //convert time to microseconds
            $microSecondsToWait = $timeToWait * 1000000;
            //Wait to maintain the API call difference of .5 seconds
            usleep($microSecondsToWait);
        }

        static::$microtimeOfLastApiCall = microtime(true);
    }
1289006
function _resolveOneIdleCall(idleQueue) {
    if (idleQueue._iC.size === 0) return;

    const iterator = idleQueue._iC.values();
    const oldestPromise = iterator.next().value;

    oldestPromise._manRes();

    // try to call the next tick
    setTimeout(() => _tryIdleCall(idleQueue), 0);
}
653835
def _limit_call_handler(self):
        
        # acquire a lock on our threading.Lock() object
        with self.limit_lock:
            # if we have no configured limit, exit.  the lock releases based on scope
            if self.limit_per_min <= 0:
                return

            now = time.time()
            # self.limits is a list of query times + 60 seconds.  In essence it is a list of times
            # that queries time out of the 60 second query window.

            # this check expires any limits that have passed
            self.limits = [l for l in self.limits if l > now]
            # and we tack on the current query
            self.limits.append(now + 60)

            # if we have more than our limit of queries (and remember, we call this before we actually
            # execute a query) we sleep until the oldest query on the list (element 0 because we append
            # new queries) times out.  We don't worry about cleanup because next time this routine runs
            # it will clean itself up.
            if len(self.limits) >= self.limit_per_min:
                time.sleep(self.limits[0] - now)
594544
public function switchQueueEntries($first, $second)
    {
        $url = $this->buildUrl('switch', [
            'value'  => $first,
            'value2' => $second
        ]);
        $request = $this->guzzle->request('GET', $url);

        return json_decode($request->getBody(), true)['result'];
    }
905999
public static <ReqT, RespT> RespT blockingUnaryCall(
      Channel channel, MethodDescriptor<ReqT, RespT> method, CallOptions callOptions, ReqT req) {
    ThreadlessExecutor executor = new ThreadlessExecutor();
    ClientCall<ReqT, RespT> call = channel.newCall(method, callOptions.withExecutor(executor));
    try {
      ListenableFuture<RespT> responseFuture = futureUnaryCall(call, req);
      while (!responseFuture.isDone()) {
        try {
          executor.waitAndDrain();
        } catch (InterruptedException e) {
          Thread.currentThread().interrupt();
          throw Status.CANCELLED
              .withDescription("Call was interrupted")
              .withCause(e)
              .asRuntimeException();
        }
      }
      return getUnchecked(responseFuture);
    } catch (RuntimeException e) {
      throw cancelThrow(call, e);
    } catch (Error e) {
      throw cancelThrow(call, e);
    }
  }
972661
public function lastCall(): Call
    {
        if ($this->callCount) {
            return $this->callVerifierFactory
                ->fromCall($this->calls[$this->callCount - 1]);
        }

        throw new UndefinedCallException(0);
    }
1030940
public function lastCall(): Call
    {
        if ($count = count($this->calls)) {
            return $this->calls[$count - 1];
        }

        throw new UndefinedCallException(0);
    }
425778
public function processCall(Session $session, Call $call)
    {
        // find a registration to call
        if (count($this->registrations) === 0) {
            $session->sendMessage(ErrorMessage::createErrorMessageFromMessage($call->getCallMessage(), 'wamp.error.no_such_procedure'));
            return false;
        }

        // just send it to the first one if we don't allow multiple registrations
        if (!$this->getAllowMultipleRegistrations()) {
            $this->registrations[0]->processCall($call);
        } else {
            $this->callQueue->enqueue($call);
            $this->processQueue();
        }

        return true;
    }
158195
function wait(testCallback, waitCallback) {
          if (!testCallback()) {
            // Wait for timeout
            if ((new Date().getTime()) - startTime < maxLoadTime) {
              Delay.setTimeout(waitCallback);
            } else {
              failed();
            }
          }
        }
1129004
public function handleRequest(RequestInterface $request, callable $next, callable $first)
    {
        return $next($request)->then(function (ResponseInterface $response) {
            $status = $response->getStatusCode();

            if ($status >= 400 && $status < 600) {
                self::handleError($status, self::getMessage($response) ?: $response->getReasonPhrase());
            }

            return $response;
        });
    }
383599
final public static function compareValues ($firstValue, $secondValue) : int
	{
		if (!self::hasValue($firstValue, $secondValue)) new ErrorCode(1001);
	    return $firstValue <=> $secondValue;
	}
99310
def call_later(self, delay, func, *args, **kwargs):
        
        # "quantize" the delay to the nearest bucket
        now = self._get_seconds()
        real_time = int(now + delay) * 1000
        real_time -= int(real_time % self._bucket_milliseconds)
        call = _BatchedCall(self, real_time, lambda: func(*args, **kwargs))
        try:
            self._buckets[real_time][1].append(call)
        except KeyError:
            # new bucket; need to add "actual" underlying IDelayedCall
            diff = (real_time / 1000.0) - now
            # we need to clamp this because if we quantized to the
            # nearest second, but that second is actually (slightly)
            # less than the current time 'diff' will be negative.
            delayed_call = self._create_delayed_call(
                max(0.0, diff),
                self._notify_bucket, real_time,
            )
            self._buckets[real_time] = (delayed_call, [call])
        return call
129524
function setRoundPointsLimit($limit, $multicall = false)
    {
        if (!is_int($limit)) {
            throw new InvalidArgumentException('limit = ' . print_r($limit, true));
        }

        return $this->execute(ucfirst(__FUNCTION__), array($limit), $multicall);
    }
1254389
final public function runMulti($idleTimeout = null, callable $callback = null)
    {
        $this->resetRetryCount();

        $successful = false;
        while (! $successful && $this->getRetryCount() < $this->getRetryLimit()) {
            $successful = $this->runOnce($idleTimeout, $callback);
            $this->increaseRetryCount();

            yield $successful;
        }
    }
259785
public void setRequestWaitTime(int requestWait) {
		this.requestWait = requestWait;
		this.getConfig().setProperty(SPIDER_REQUEST_WAIT, Integer.toString(requestWait));
	}
1266629
public function handleRequest(RequestInterface $request, callable $next, callable $first)
    {
        return $next($request)->then(function (ResponseInterface $response) {
            return $response;
        }, function (Exception $exception) use ($request, $next, $first) {
            if ($exception instanceof OauthAccessTokenAuthenticationException) {
                // Mark access token as expired and with that ensure that the authentication plugin gets a new
                // access token.
                $this->auth->getTokenStorage()->markExpired();
                $promise = $first($request);

                return $promise->wait();
            }

            throw $exception;
        });
    }
38532
public function start($checkInterval = 1000000, $timeLimit = null)
    {
        $totalTime = 0;
        $this->watching = true;

        while ($this->watching) {
            usleep($checkInterval);
            $totalTime += $checkInterval;

            if (null !== $timeLimit && $totalTime > $timeLimit) {
                break;
            }

            foreach ($this->getTracker()->getEvents() as $event) {
                $trackedResource = $event->getTrackedResource();

                // fire global event
                $this->getEventDispatcher()->dispatch(
                    'resource_watcher.all',
                    $event
                );

                // fire specific trackingId event
                $this->getEventDispatcher()->dispatch(
                    sprintf('resource_watcher.%s', $trackedResource->getTrackingId()),
                    $event
                );
            }
        }

        $this->watching = false;
    }