threading.py 779 B

1234567891011121314151617181920212223242526
  1. import time
  2. from concurrent.futures import Future, TimeoutError
  3. from itertools import count
  4. from threading import Thread, Event, Lock
  5. def run_in_background(func: callable, *args, **kwargs) -> Future:
  6. """ run f(*args, **kwargs) in background and return Future for its outputs """
  7. future = Future()
  8. def _run():
  9. try:
  10. future.set_result(func(*args, **kwargs))
  11. except BaseException as e:
  12. future.set_exception(e)
  13. Thread(target=_run).start()
  14. return future
  15. def run_forever(func: callable, *args, **kwargs):
  16. """ A function that runs a :func: in background forever. Returns a future that catches exceptions """
  17. def repeat():
  18. while True:
  19. func(*args, **kwargs)
  20. return run_in_background(repeat)