Windows Service in Python -


i following solution provided in following link create windows service python not hang in stopping state when try stop after days running.

timeout , windows services long running processes (python)

the problem facing after start service seems run once , service in windows service manager have tasks disabled can not stop or restart it. below code. have removed real tasks want perform , replace dummy service add 1 variable (x) every-time runs , write log file.

i appreciate tip in trying find mistake.

# -*- coding: utf-8 -*- """ created on thu jul 27 09:07:29 2017  @author:aaaa """  import threading import logging import logging.config import win32api import win32serviceutil import win32event   class interruptedexception(exception):     pass  class workerthread(threading.thread):     def __init__(self, controller):         self._controller = controller         self._stop = threading.event()         super(workerthread, self).__init__()          self.x=0          #------------------------------------------------------------------------------         # creating logger         #------------------------------------------------------------------------------         logging.config.fileconfig(r'c:\temp\teste_logging.conf')         # create logger         self.logger = logging.getlogger('teste')         self.logger.debug("serviço criado")      def stop(self):         self._stop.set()      def stopped(self):         return self._stop.isset()      def run(self):         try:            # insert code want run service here            # rather "execfile(.../.../blah)" do:            # can have code throw interruptedexception if code needs exit            # check if self.stopped , cleanly exit            self.x+=1            self.logger.debug('x = {}'.format(self.x))          except interruptedexception e:            # forcefully quitting             self.logger.debug('interruption exception - {}'.format(str(e)))            pass         except exception e:             self.logger.debug('unexpected error - {}'.format(str(e)))             pass            # oh oh, did not anticipate this, better report windows or log         finally:            # close/release connections, handles, files etc.            # ok, can stop            win32event.setevent(self._controller)  class test_service(win32serviceutil.serviceframework):     _svc_name_ = "pytest"    _svc_display_name_ = "test event service"    _svc_description_ = "service teste python service"     def __init__(self, args):        win32serviceutil.serviceframework.__init__(self, args)        self.hwaitstop = win32event.createevent(none, 0, 0, none)             self.hwaitdone = win32event.createevent(none, 0, 0, none)         #logger        self.logger=logging.getlogger('teste.service')         #create worker         self.worker = workerthread(self.hwaitdone)     def svcdorun(self):         import servicemanager               servicemanager.logmsg(servicemanager.eventlog_information_type,                               servicemanager.pys_service_started,(self._svc_name_, ''))           #worker = workerthread(self.hwaitdone,self.dconfig)         self.worker.start()          while true:             # wait service stop signal             rc = win32event.waitformultipleobjects([self.hwaitstop, self.hwaitdone],win32event.infinite,60000)              # check see if self.hwaitstop happened part of windows service management             if rc == 0:                 # stop signal encountered                 servicemanager.loginfomsg(self._svc_name_ + " - stopped!")  #for event log                 break              if rc == 1:                 # wait until worker has finished                 self.worker.join()                  # determine worker state if need start again (because run finished)                 # or whatever                 if not self.worker.need_to_start_again():                     break                  self.worker.start()  def ctrlhandler(ctrltype):    return true  if __name__ == '__main__':       win32api.setconsolectrlhandler(ctrlhandler, true)       win32serviceutil.handlecommandline(test_service) 

here configuration of logging module. save in text file , save teste_logging.conf

[loggers] keys=root,teste  [handlers] keys=logfile,consolehandler  [formatters] keys=simpleformatter,logfileformatter  [logger_root] level=debug handlers=consolehandler  [logger_teste] level=debug handlers=logfile qualname=teste propagate=0  [formatter_logfileformatter] format=%(asctime)s %(name)-12s: %(levelname)s %(message)s  [formatter_simpleformatter] format=%(asctime)s - %(name)s - %(levelname)s - %(message)s datefmt=  [handler_consolehandler] class=streamhandler level=debug formatter=simpleformatter args=(sys.stdout,)  [handler_logfile] class=handlers.rotatingfilehandler level=debug args=(r'c:\temp\pyteste.log','a',5000000,20) formatter=logfileformatter 

i have found reason why services task disabled. forgot implement svcstop function.

def svcstop(self):     self.reportservicestatus(win32service.service_stop_pending)     win32event.setevent(self.hwaitstop)     

nevertheless still runing once.


Comments

Popular posts from this blog

php - Vagrant up error - Uncaught Reflection Exception: Class DOMDocument does not exist -

vue.js - Create hooks for automated testing -

Add new key value to json node in java -