title: Python Tweepy streaming with multitasking
body: <p>in Python 2.7 I am successful in using the following code to listen to a direct message stream on an account:</p>
  
  <pre><code>from tweepy import Stream
  from tweepy import OAuthHandler
  from tweepy import API
  from tweepy.streaming import StreamListener
  
  # These values are appropriately filled in the code
  
  consumer_key = '######'
  consumer_secret = '######'
  access_token = '######'
  access_token_secret = '######'
  
  class StdOutListener( StreamListener ):
  
      def __init__( self ):
          self.tweetCount = 0
  
      def on_connect( self ):
          print("Connection established!!")
  
      def on_disconnect( self, notice ):
          print("Connection lost!! : ", notice)
  
      def on_data( self, status ):
          print("Entered on_data()")
          print(status, flush = True)
          return True
          # I can add code here to execute when a message is received, such as slicing the message and activating something else
  
      def on_direct_message( self, status ):
          print("Entered on_direct_message()")
          try:
              print(status, flush = True)
              return True
          except BaseException as e:
              print("Failed on_direct_message()", str(e))
  
      def on_error( self, status ):
          print(status)
  
  def main():
  
      try:
          auth = OAuthHandler(consumer_key, consumer_secret)
          auth.secure = True
          auth.set_access_token(access_token, access_token_secret)
  
          api = API(auth)
  
          # If the authentication was successful, you should
          # see the name of the account print out
          print(api.me().name)
  
          stream = Stream(auth, StdOutListener())
  
          stream.userstream()
  
      except BaseException as e:
          print("Error in main()", e)
  
  if __name__ == '__main__':
      main()
  </code></pre>
  
  <p>This is great, and I can also execute code when I receive a message, but the jobs I'm adding to a work queue need to be able to stop after a certain amount of time. I'm using a popular start = time.time() and subtracting current time to determine elapsed time, but this streaming code does not loop to check the time. I just waits for a new message, so the clock is never checked so to speak.</p>
  
  <p>My question is this: How can I get streaming to occur and still track time elapsed? Do I need to use multithreading as described in this article? <a href="http://www.tutorialspoint.com/python/python_multithreading.htm" rel="nofollow">http://www.tutorialspoint.com/python/python_multithreading.htm</a></p>
  
  <p>I am new to Python and having fun playing around with hardware attached to a Raspberry Pi. I have learned so much from Stackoverflow, thank you all :)</p>