Search code examples
pythonzeromq

How to wait program until the function give return value?


I have code like this :

zmq = Zmq_Connector_Mod.DWX_ZeroMQ_Connector()
zmq._GET_HIST_INDICATORS_(_symbol, 'C1')
sleep(random() * 5 )
c1_path = zmq._GET_DATA_()

zmq = Zmq_Connector_Mod.DWX_ZeroMQ_Connector()
zmq._GET_HIST_INDICATORS_(_symbol, 'BASELINE')
sleep(random() * 5 )
baseline_path = zmq._GET_DATA_()

zmq = Zmq_Connector_Mod.DWX_ZeroMQ_Connector()
zmq._GET_HIST_INDICATORS_(_symbol, 'C2')
sleep(random() * 5 )
c2_path = zmq._GET_DATA_()

zmq = Zmq_Connector_Mod.DWX_ZeroMQ_Connector()
zmq._GET_HIST_INDICATORS_(_symbol, 'EXIT')
sleep(random() * 5 )
exit_path = zmq._GET_DATA_()

I have a problem when zmq._GET_DATA_() is running, it doesn't have returned value, because zmq._GET_HIST_INDICATORS_() function needs a couple seconds to return the value. I already used sleep(), but it's not efficient because when I try to run this code in another device that slower than mine, it just not helping. How to wait program from execute the zmq._GET_DATA_() until zmq._GET_HIST_INDICATORS_() has returned the value without using sleep() that need time, meanwhile every device has different running time to execute the code ?


Solution

  • It looks like you are using a message queue, so there must be a documented async way of doing this, but you may try something like the following:

    exit_path = None
    while exit_path is None:
        try:
            exit_path = zmq._GET_DATA_()
        except AttributeError:
            exit_path = None
            sleep(1)
    

    This should check once every second to see if the data is available.