python-daemon - 在里面运行线程

时间:2017-12-21 15:57:42

标签: python multithreading python-daemon

我正在使用python-daemon,但我在守护进程中有一个线程偶尔检查一个串口:

context = daemon.DaemonContext(pidfile=daemon.pidfile.TimeoutPIDLockFile('/var/run/gpstemp.pid'),
                          uid = 0,
                          gid = 4,
                          umask = 0o002,
                          stdout = sys.stdout,  # change these for deployment
                          stderr =sys.stderr,   # change these for deployment
                          chroot_directory= None,
                          working_directory='/home/debian/gpstemp'
app = App()
with context:
    app.run()

线程运行:

class App():
    def __init__(self, port = 5556):
    ...
        # Handle all those threading things
        self.__sem = Lock()
        self.interval = 60.0  # interval between time updates in seconds
        self.worker = Thread(target = self._get_datetime_worker)
    def run(self):
        self.worker.start()
...
    def _get_datetime_worker(self):
        while not self.exit.is_set():
            self._get_datetime()
            self.exit.wait(self.interval)

我正在使用systemctl使用.service文件启动和停止它。 当我跑:     sudo systemctl stop myservice

它在返回前等待60秒。如何通过systemctl立即终止服务中的线程。我考虑将上下文传递给App,然后重新定义:

 context.signal_map = {
     signal.SIGTERM: app.shutdown,
     signal.SIGHUP: app.shutdown,
     }

然后向App添加关闭方法:

def shutdown(self, *args):
    self.exit.set()
    self.worker.join()

但是,这不会让上下文破坏PID并且不会退出上下文。我还应该在关机方法中添加什么才能使事情正常工作?

库尔特

1 个答案:

答案 0 :(得分:2)

在你杀死主程序时,我是否正确理解你想杀死线程?您可以通过设置daemon=True

来完成此操作
def run(self):
    self.worker.daemon = True
    self.worker.start()