I have written a python script which will be installed in as windows service. Below is the code:
import datetime
import logging
from logging.handlers import RotatingFileHandler
import os
import time
from random import randint
import win32serviceutil
import win32service
import win32event
import servicemanager
import socket
def setup_logger(logger_name, log_file, level=logging.ERROR):
log_formatter = logging.Formatter('%(asctime)s %(message)s')
my_handler = RotatingFileHandler(log_file, maxBytes=100 * 1024 * 1024, backupCount=5)
my_handler.setFormatter(log_formatter)
my_handler.setLevel(level)
l = logging.getLogger(logger_name)
l.handlers[:] = []
l.addHandler(my_handler)
curr_path = os.getcwd()
log_file = "F:\\Projects\\TestService\\logs\\application.log"
setup_logger('debug', log_file)
log = logging.getLogger('debug')
class AppServerSvc(win32serviceutil.ServiceFramework):
_svc_name_ = "test_service"
_svc_display_name_ = "Test Service"
def __init__(self, args):
win32serviceutil.ServiceFramework.__init__(self, args)
self.hWaitStop = win32event.CreateEvent(None, 0, 0, None)
socket.setdefaulttimeout(60)
self.isrunning = False
def SvcStop(self):
self.ReportServiceStatus(win32service.SERVICE_STOP_PENDING)
win32event.SetEvent(self.hWaitStop)
self.isrunning = False
def SvcDoRun(self):
servicemanager.LogMsg(servicemanager.EVENTLOG_INFORMATION_TYPE,
servicemanager.PYS_SERVICE_STARTED,
(self._svc_name_, ''))
self.isrunning = True
self.main()
def main(self):
while self.isrunning:
log.error("Running {}".format(randint(00, 99)))
time.sleep(10)
if __name__ == '__main__':
win32serviceutil.HandleCommandLine(AppServerSvc)
I have run the command python test_service.py install
to install the service and got the correct output Installing service test_service Service installed
. When I open services tab I can see my service listed there. When I click on start service I am getting below error:
Can anyone please tell me what is wrong in the code due to which its not starting the service. Please help. Thanks
UPDATE:
I ran the service in debug mode in cmd
and looks like it is working fine. But from the services tab, its not working and showing above error.
> python test_service.py debug
Debugging service test_service - press Ctrl+C to stop.
Info 0x40001002 - The test_service service has started.
When starting the service, it gives same error:
> python test_service.py start
Starting service test_service
Error starting service: The service did not respond to the start or control request in a timely fashion.
Not sure why its not running and in debug mode it runs fine. Please help.