Skip to content Skip to sidebar Skip to footer

Python - Waiting For Variable Change

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 immedi

Solution 1:

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

Solution 2:

Here is an example with threading event:

import threading
from time import sleep

evt = threading.Event()
result = Nonedefbackground_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)

Post a Comment for "Python - Waiting For Variable Change"