Guest User

Untitled

a guest
Dec 14th, 2018
79
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
text 1.59 KB | None | 0 0
  1. # -*- coding: utf-8 -*-
  2. from __future__ import unicode_literals
  3.  
  4. import logging
  5. import threading
  6. import time
  7.  
  8. log = logging.getLogger(__name__)
  9.  
  10. CADENCE = 1.0 # in seconds
  11. SHUTDOWN_TIMEOUT = 5
  12. _should_poll = threading.Event()
  13. _task = None
  14.  
  15.  
  16. class _Poller(threading.Thread):
  17.  
  18. def __init__(self, should_poll, *args, **kw):
  19.  
  20. super(_Poller, self).__init__(*args, **kw)
  21.  
  22. # threading.Event instance that controls thread lifecycle
  23. self._should_poll = should_poll
  24.  
  25. # Make this a daemon thread so it will die with the main thread
  26. self.daemon = True
  27.  
  28. def run(self):
  29. """ Actually run the poller loop.
  30. """
  31.  
  32. while self._should_poll.isSet():
  33. try:
  34. self._execute()
  35. except Exception:
  36. log.exception("poller encountered an exception")
  37. finally:
  38. time.sleep(CADENCE)
  39.  
  40. log.info("poller run loop has exited")
  41.  
  42. def _execute(self):
  43. """ Execute a poller iteration
  44. """
  45.  
  46. # insert poller logic here
  47. pass
  48.  
  49.  
  50. def start():
  51. """ start polling
  52. """
  53.  
  54. global _task
  55.  
  56. if _task is not None:
  57. # Shutdown an existing poller
  58. log.warning("found an existing poller, shutting it down")
  59. _task.shutdown(timeout=SHUTDOWN_TIMEOUT)
  60.  
  61. _should_poll.set()
  62. _task = _Poller(_should_poll)
  63.  
  64. log.info("starting to poll")
  65. _task.start()
  66.  
  67.  
  68. def stop():
  69. """ stop polling
  70. """
  71.  
  72. global _task
  73.  
  74. _should_poll.clear()
  75.  
  76. if _task is not None:
  77. log.info("poller is shutting down...")
  78. _task.join(timeout=SHUTDOWN_TIMEOUT)
Add Comment
Please, Sign In to add comment