Python多线程服务

2024-04-26 05:27:37 发布

您现在位置:Python中文网/ 问答频道 /正文

我正在尝试用几个线程在python上创建windows服务。 我写的代码可以按我的需要工作,但我不明白它是如何破坏线程的! 为什么while循环中的break会中断不在while循环中的线程?你知道吗

import win32serviceutil
import win32service
import win32event
import servicemanager
import threading
from classifier import clf, refit

class AppServerSvc (win32serviceutil.ServiceFramework):
    _svc_name_ = "MyService"
    _svc_display_name_ = "My Service"

    def __init__(self,args):
        win32serviceutil.ServiceFramework.__init__(self,args)
        self.hWaitStop = win32event.CreateEvent(None,0,0,None)

    def SvcStop(self):
        self.ReportServiceStatus(win32service.SERVICE_STOP_PENDING)
        win32event.SetEvent(self.hWaitStop) 

    def SvcDoRun(self):
        servicemanager.LogMsg(servicemanager.EVENTLOG_INFORMATION_TYPE,
                          servicemanager.PYS_SERVICE_STARTED,
                          (self._svc_name_,'')) 
        self.main()

    def main(self):
        t1 = threading.Thread(target=clf)
        t2 = threading.Thread(target=refit)
        t1.start()
        t2.start()
        while True:        
            rc = win32event.WaitForSingleObject(self.hWaitStop, 100)
            if rc == win32event.WAIT_OBJECT_0:
                break  

if __name__ == '__main__':
    win32serviceutil.HandleCommandLine(AppServerSvc)   

Tags: nameimportselfmaindefserviceutilmanager
1条回答
网友
1楼 · 发布于 2024-04-26 05:27:37

SvcDoRun返回时,服务进程终止。这会使线程与进程的其余部分一起下降。如果希望线程继续执行,则必须使进程保持活动状态。换句话说,不要从SvcDoRun返回。你知道吗

相关问题 更多 >