Background service thread.
| 97 | |
| 98 | |
| 99 | class bgThread(threading.Thread): |
| 100 | """Background service thread.""" |
| 101 | |
| 102 | def __init__(self, name=None, **kwargs): |
| 103 | super().__init__() |
| 104 | self.__is_shutdown = threading.Event() |
| 105 | self.__is_stopped = threading.Event() |
| 106 | self.daemon = True |
| 107 | self.name = name or self.__class__.__name__ |
| 108 | |
| 109 | def body(self): |
| 110 | raise NotImplementedError() |
| 111 | |
| 112 | def on_crash(self, msg, *fmt, **kwargs): |
| 113 | print(msg.format(*fmt), file=sys.stderr) |
| 114 | traceback.print_exc(None, sys.stderr) |
| 115 | |
| 116 | def run(self): |
| 117 | body = self.body |
| 118 | shutdown_set = self.__is_shutdown.is_set |
| 119 | try: |
| 120 | while not shutdown_set(): |
| 121 | try: |
| 122 | body() |
| 123 | except Exception as exc: # pylint: disable=broad-except |
| 124 | try: |
| 125 | self.on_crash('{0!r} crashed: {1!r}', self.name, exc) |
| 126 | self._set_stopped() |
| 127 | finally: |
| 128 | sys.stderr.flush() |
| 129 | os._exit(1) # exiting by normal means won't work |
| 130 | finally: |
| 131 | self._set_stopped() |
| 132 | |
| 133 | def _set_stopped(self): |
| 134 | try: |
| 135 | self.__is_stopped.set() |
| 136 | except TypeError: # pragma: no cover |
| 137 | # we lost the race at interpreter shutdown, |
| 138 | # so gc collected built-in modules. |
| 139 | pass |
| 140 | |
| 141 | def stop(self): |
| 142 | """Graceful shutdown.""" |
| 143 | self.__is_shutdown.set() |
| 144 | self.__is_stopped.wait() |
| 145 | if self.is_alive(): |
| 146 | self.join(THREAD_TIMEOUT_MAX) |
| 147 | |
| 148 | |
| 149 | def release_local(local): |