Rate limit exceeded

前端 未结 1 1738
天涯浪人
天涯浪人 2021-01-27 05:36

I ran my code that get some tweets with number = 50000 tweets but after getting some of them i got this error . I reviewed the below links in the error message but couldn\'t get

相关标签:
1条回答
  • 2021-01-27 06:15

    in twitter4j there is RateLimitStatus object. You can access this object after some api calls. For example:

    User user = twitter.showUser(userId);
    user.getRateLimitStatus();
    //OR
    IDs followerIDs = twitter.getFollowersIDs(user.getScreenName(), -1);
    followerIDs.getRateLimitStatus();
    //OR
    QueryResult result = twitter.search(query);
    result.getRateLimitStatus();
    

    And maybe you can use a function to handle rate limit like this:

    private void handleRateLimit(RateLimitStatus rateLimitStatus) {
        //throws NPE here sometimes so I guess it is because rateLimitStatus can be null and add this condition
        if (rateLimitStatus != null) {
            int remaining = rateLimitStatus.getRemaining();
            int resetTime = rateLimitStatus.getSecondsUntilReset();
            int sleep = 0;
            if (remaining == 0) {
                sleep = resetTime + 1; //adding 1 more seconds
            } else {
                sleep = (resetTime / remaining) + 1; //adding 1 more seconds
            }
    
            try {
                Thread.sleep(sleep * 1000 > 0 ? sleep * 1000 : 0);
            } catch (InterruptedException e) {
                e.printStackTrace();
            }
        }
    }
    

    or maybe this:

    private void handleRateLimit(RateLimitStatus rateLimitStatus) {
        int remaining = rateLimitStatus.getRemaining();
        if (remaining == 0) {
            int resetTime = rateLimitStatus.getSecondsUntilReset() + 5;
            int sleep = (resetTime * 1000);
            try {
                Thread.sleep(sleep > 0 ? sleep : 0);
            } catch (InterruptedException e) {
                e.printStackTrace();
            }
        }
    }
    

    Hope this helps.

    Any other/better methods would also be appreciated.

    0 讨论(0)
提交回复
热议问题