2016-03-02 96 views
0

我目前正在实施一项计划,要求我使用Twitter4J收集推文并存储它们。但是,我意识到您只能使用Twitter的Developer API每15分钟发出180个请求。费率限制预防[Twitter4J]

由于这个原因,我创建了一个方法,在程序获得10条推文后停止15分钟,而我的消费者和访问键重置速率限制。但是,有时速率限制仍然会在获得这10条推文之间耗尽?所以我想要做的是改变方法,以便由于速率限制即将停止而停止。

例如...

if (rate limit = 0){ 
    stop program until rate limit resets 
} 

然而,我的方法只是现在只是实现了一个计数器,并在该计数器达到10,它停了,这是不是很经济的或有效的。我认为10条推文将是一个适当的数量,但显然不是。 这里是我的方法...

public void getRateLimit() throws TwitterException{ 
     if (count == 10){ 
      try { 
       System.out.println("Rate Limit is about to be exhausted for resource..."); 
       System.out.println("Please wait for 15 minutes, while it resets..."); 
       TimeUnit.MINUTES.sleep(15); 
       count = 0; 
      } catch (InterruptedException e) { 
       System.out.println(e); 
      } 
} 

我怎么可能会改变这一点,以便它运行时的速率限制即将用完而停止,只有当它补充开始。 感谢您的帮助。

回答

1

我以前遇到同样的问题,我尝试计算1次请求的时间花费。如果该请求低于5500毫秒比程序等待它达到5500毫秒,它对我来说完美的工作,

你可以问为什么5500毫秒,这是因为180请求15分钟使每个请求5秒。

这里是我使用的代码,希望它有帮助。

do { 
    final long startTime = System.nanoTime(); 
    result = twitter.search(query); 
    statuses = result.getTweets(); 
    for (Status status : statuses) { 
     tweet = new Tweet(status); 
     userProfile = new UserProfile(status.getUser()); 

     imageDownloader.getMedia(tweet.mediaEntities); 
     imageDownloader.getProfilePhoto(userProfile.ProfileImageUrl); 

     System.out.println(tweet); 
     System.out.println(userProfile); 
    } 
    final long duration = System.nanoTime() - startTime; 
    if ((5500 - duration/1000000) > 0) { 
     logger.info("Sleep for " + (6000 - duration/1000000) + " miliseconds"); 
     Thread.sleep((5500 - duration/1000000)); 
    } 
} while ((query = result.nextQuery()) != null); 
+0

我对这种情况找到了更好的解决方案,这里查看这个答案https://stackoverflow.com/a/45199642/2183174 – kadir