threading.py 712 B

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