Not a member of Pastebin yet?
Sign Up,
it unlocks many cool features!
- # -*- coding: utf-8 -*-
- from __future__ import unicode_literals
- import logging
- import threading
- import time
- log = logging.getLogger(__name__)
- CADENCE = 1.0 # in seconds
- SHUTDOWN_TIMEOUT = 5
- _should_poll = threading.Event()
- _task = None
- class _Poller(threading.Thread):
- def __init__(self, should_poll, *args, **kw):
- super(_Poller, self).__init__(*args, **kw)
- # threading.Event instance that controls thread lifecycle
- self._should_poll = should_poll
- # Make this a daemon thread so it will die with the main thread
- self.daemon = True
- def run(self):
- """ Actually run the poller loop.
- """
- while self._should_poll.isSet():
- try:
- self._execute()
- except Exception:
- log.exception("poller encountered an exception")
- finally:
- time.sleep(CADENCE)
- log.info("poller run loop has exited")
- def _execute(self):
- """ Execute a poller iteration
- """
- # insert poller logic here
- pass
- def start():
- """ start polling
- """
- global _task
- if _task is not None:
- # Shutdown an existing poller
- log.warning("found an existing poller, shutting it down")
- _task.shutdown(timeout=SHUTDOWN_TIMEOUT)
- _should_poll.set()
- _task = _Poller(_should_poll)
- log.info("starting to poll")
- _task.start()
- def stop():
- """ stop polling
- """
- global _task
- _should_poll.clear()
- if _task is not None:
- log.info("poller is shutting down...")
- _task.join(timeout=SHUTDOWN_TIMEOUT)
Add Comment
Please, Sign In to add comment