13

I have a Python script that opens a websocket to the Twitter API and then waits. When an event is passed to the script via amq, I need to open a new websocket connection and immediately close the old one just as soon as the new connection is registered.

It looks something like this:

stream = TwitterStream()
stream.start()

for message in broker.listen():
    if message:
        new_stream = TwitterStream()
        # need to close the old connection as soon as the 
        # new one connects here somehow
        stream = new_stream()

I'm trying to figure out how I'd establish a 'callback' in order to notify my script as to when the new connection is established. The TwitterStream class has a "is_running" boolean variable that I can reference, so I was thinking perhaps something like:

while not new_stream.is_running:
    time.sleep(1)

But it seems kind of messy. Does anyone know a better way to achieve this?

Hanpan
  • 10,013
  • 25
  • 77
  • 115

2 Answers2

13

A busy loop is not the right approach, since it obviously wastes CPU. There are threading constructs that let you communicate such events, instead. See for example: http://docs.python.org/library/threading.html#event-objects

Assaf Lavie
  • 73,079
  • 34
  • 148
  • 203
5

Here is an example with threading event:

import threading
from time import sleep

evt = threading.Event()
result = None
def background_task(): 
    global result
    print("start")
    result = "Started"
    sleep(5)
    print("stop")
    result = "Finished"
    evt.set()
t = threading.Thread(target=background_task)
t.start()
# optional timeout
timeout=3
evt.wait(timeout=timeout)
print(result)
Tomek C.
  • 584
  • 9
  • 12