I am making api calls to the Alpaca brokerage and sometimes indefinitely not receiving an answer. I would like to be able to wait for response for a minute and then cancel and retry. Something like this:
import threading import time class LongFunctionInside(object): lock_state = threading.Lock() working = False def long_function(self, timeout): self.working = True timeout_work = threading.Thread(name="thread_name", target=self.work_time, args=(timeout,)) timeout_work.setDaemon(True) timeout_work.start() while True: # endless/long work time.sleep(0.1) # in this rate the CPU is almost not used if not self.working: # if state is working == true still working break self.set_state(True) def work_time(self, sleep_time): # thread function that just sleeping specified time, # in wake up it asking if function still working if it does set the secured variable work to false time.sleep(sleep_time) if self.working: self.set_state(False) def set_state(self, state): # secured state change while True: self.lock_state.acquire() try: self.working = state break finally: self.lock_state.release() lw = LongFunctionInside() lw.long_function(10)
does not work because the api call is not something short like a print function that can be followed by a
if not self.working: check. I have tried to find and fix solutions for hours and am lost. It seems like a simple problem and one that probably is merely two parallel thread processes with one keeping track of time and then killing the other and then retrying the whole thing. I just don’t know how to do this. I have seen solutions for UNIX but I am on Windows. Any help appreciated! Thanks!