python中的Windows服务在短时间后停止

时间:2015-10-15 16:15:42

标签: python windows-services

我在python中有一个Windows服务(在网站上的教程之后制作)并且它正在工作,但只有很短的时间(如1-2分钟)。

import win32serviceutil
import win32service
import win32event
import servicemanager
import socket
import time
import logging

logging.basicConfig(
    filename = 'c:\\temp\\service.log',
    level = logging.DEBUG, 
    format = '[Service] %(levelname)-7.7s %(message)s'
)

class HelloWorldSvc (win32serviceutil.ServiceFramework):
    _svc_name_ = "S-Service"
    _svc_display_name_ = "Service Service"

    _host = '0.0.0.0'
    _port = 6969
    _back = 5
    _size = 4096

    def __init__(self,args):
        win32serviceutil.ServiceFramework.__init__(self,args)
        self.stop_event = win32event.CreateEvent(None,0,0,None)
        socket.setdefaulttimeout(60)
        self.stop_requested = False

    def SvcStop(self):
        self.ReportServiceStatus(win32service.SERVICE_STOP_PENDING)
        win32event.SetEvent(self.stop_event)
        logging.info('Stopping service ...')
        self.stop_requested = True

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

    def main(self):
        logging.info(' ** Hello PyWin32 World ** ')
        # Simulate a main loop
        while 1:
            if self.stop_requested:
                logging.info('A stop signal was received: Breaking main loop ...')
                break
            #time.sleep(5)
            logging.info("Starting server at %s" % time.ctime())
            s = socket.socket(socket.AF_INET, socket.SOCK_STREAM) 
            s.bind((self._host, self._port)) 
            s.listen(self._back)
            while 1:
                client, address = s.accept()
                data = client.recv(self._size)
                logging.info('Recivied command %s' % data)
                if data: 
                    client.send(b"Recevied:" + data)
                client.close()
        return

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

它正在工作,我可以发送命令并收到但1-2分钟后会停止 有谁知道问题出在哪里?
谢谢!

0 个答案:

没有答案