Not a member of Pastebin yet?
Sign Up,
it unlocks many cool features!
- class WaiterTimeout(Exception):
- pass
- class Waiter(object):
- """
- w = Waiter()
- run_some_func_with_callback(callback=lambda x: w.stop(x))
- try:
- r = w.timeout(5) # wait 5 seconds for timeout
- except WaiterTimeout:
- print("timeout occured")
- else:
- print("result: {}".format(r))
- """
- def __init__(self, spin=None):
- self.event = threading.Event()
- self.result = None
- def wait(self, timeout=None, spin=0):
- if timeout is None or not spin:
- if self.event.wait(timeout):
- return self.result
- else:
- raise WaiterTimeout
- total = 0
- while total < timeout:
- if self.event.wait(spin):
- return self.result
- total += spin
- raise WaiterTimeout
- def stop(self, result=None):
- self.result = result
- self.event.set()
- def clear(self):
- self.event.clear()
- self.result = None
Add Comment
Please, Sign In to add comment