如何在确切的日期断开流媒体;时间

时间:2014-10-07 03:59:53

标签: python twython

我正在使用Python和TwythonStreamer来传播来自Twitter的状态。目前,我通过计算收集的推文数量来设置自动断开连接,如下所示:

首先我全局设置

max_tweets = 8000

然后在def on_success(self, tweet)中,我有一个代码段:

if (count >= max_tweets):
  self.disconnect()
  return False

如何在'2014年10月12日00:00:00'确切的日期和时间断开信息流

1 个答案:

答案 0 :(得分:0)

由于流过程的作用类似于serverForever服务器(除非您传递重试次数)

twython/streaming/api.py._request
if self.retry_count and (self.retry_count - retry_counter) > 0:
    time.sleep(self.retry_in)
    retry_counter += 1
    _send(retry_counter)

停止该过程的唯一方法是,当某些条件成立时,在self.shutdown回调中执行on_success本身,或者,难以理解:包裹流使用进程,保留其pid或引用,并从其他进程中删除它(如注释here

编辑:流媒体包装器及其调用者的方法

class Your_Streamer(TwythonStreamer, Process):
    def __init__(self, ):
        Process.__init__(self)
        consumer_key, consumer_secret, oauth_token,oauth_secret = '','','','' #your twitter keys
        super(SocialVane_Streamer, self).__init__(consumer_key, consumer_secret, oauth_token,oauth_secret)
    def run (self):
        keyword_list =[] #the keywords you want to monitorize 
        if keyword_list:
            logger.info("start_monitoring, tracking keywords = %s" % ','.join(keyword_list))        
            self.statuses.filter(track=','.join(keyword_list))
    def on_error(self, status_code, data):
        print status_code
        # Want to stop trying to get data because of the error?
        # Uncomment the next line!
        # self.disconnect()                
    def on_success(self, data):
        if 'text' in data:
            pass #do what you need

现在来自另一个主题,可以是main方法或您想要的方法

stream = Your_Streamer()
if stream.ready():
    stream.start()
    logger.debug("pid %i created" % stream.pid)
    while not your_stop_condition: 
        import time
        time.sleep(1000) #some sleep
    stream.terminate()