2013-04-08 32 views
1

我正在使用Twitter流在某些過濾的推文上進行採樣。不過,我只想提取一小部分推文,因此我使用時間來控制關閉流的時間。同時我寫信給一個文件。但是,在我退出程序之前,流會繼續並不會關閉。任何原因爲什麼?我使用Scala的做到這一點,這裏是我的代碼:Twitter4j流關機

def simpleStatusListener = new StatusListener() { 
    def onStatus(status: Status) { 
     appendToFile("/tmp/stream.txt",status.getText) 
    } 
    def onDeletionNotice(statusDeletionNotice: StatusDeletionNotice) {} 
    def onTrackLimitationNotice(numberOfLimitedStatuses: Int) {} 
    def onException(ex: Exception) { ex.printStackTrace } 
    def onScrubGeo(arg0: Long, arg1: Long) {} 
    def onStallWarning(warning: StallWarning) {} 
    } 

val twitter = new TwitterFactory().getInstance 

twitterStream.addListener(simpleStatusListener) 

val now = System.nanoTime 
if((System.nanoTime-now)/1000000 > 10){ 
     twitterStream.cleanUp 
     twitterStream.shutdown 
    } 
+0

如果你要一段時間(例如10秒後),你必須使用定時關機後您的流。你的if塊幾乎肯定只執行一次,當它執行時'System.nanoTime-now'的差異只有幾個納秒,因此流永遠不會關閉 – 2013-04-08 06:45:30

回答

2

在您關閉流很可能會在那裏你計算now變量的行後立即執行該位。所以,如果條件(System.nanoTime-now)/1000000 > 10將保持不可能。這裏有一個解決方案:

def simpleStatusListener = new StatusListener() { 
    def onStatus(status: Status) { 
    appendToFile("/tmp/stream.txt",status.getText) 
    } 
    def onDeletionNotice(statusDeletionNotice: StatusDeletionNotice) {} 
    def onTrackLimitationNotice(numberOfLimitedStatuses: Int) {} 
    def onException(ex: Exception) { ex.printStackTrace } 
    def onScrubGeo(arg0: Long, arg1: Long) {} 
    def onStallWarning(warning: StallWarning) {} 
} 

val twitter = new TwitterFactory().getInstance 

twitterStream.addListener(simpleStatusListener) 

//scheduling the closing of the stream 
val interval = 10 * 1000000 

val timer = new Timer() 

val cancelTask = new TimerTask { 
    def run() { 
    twitterStream.cleanup() 
    twitterStream.shutdown() 
    } 
} 

timer.schedule(cancelTask, interval)