2016-03-02 93 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