Error 1053: The service did not
最近在把Python的定时程序放进Windows服务时遇到了上述的问题‘错误1053:服务没有及时响应启动或控制请求’ 或者 ‘Error 1053: The service did not respond to the start or control request in a timely fashion’。
可以正常安装python PythonFileName.py install
,
不能正常启动python PythonFileName.py start
。
尝试使用python PythonFileName.py debug
检查代码,没有发现代码问题,考虑应该是环境问题。
最终在StackOverflow的 Can't start Windows service written in Python (win32serviceutil) 中找到了 BuvinJ 的回答:“It might prove useful in this case to also add these directories to your system path: C:\Python27\Lib\site-packages\win32 and C:\Python27\Lib\site-packages\pywin32_system32. That will let you use pythonservice more easily. ”
解决办法
在cmd中输入
setx /M PATH "%PATH%;C:\Python27;C:\Users\Administrator\Anaconda2\Scripts;C:\Users\Administrator\Anaconda2\Lib\site-packages\pywin32_system32;C:\Users\Administrator\Anaconda2\Lib\site-packages\win32"
回车,增加两个路径的引用。然后就能启动服务了。
具体的Windows服务Python代码:
import sys
import win32serviceutil
import win32service
import win32event
import servicemanager
import winerror
class StockRecommendRunLoop(win32serviceutil.ServiceFramework):
_svc_name_ = "StockRecommendRunLoop"
_svc_display_name_ = "Stock Recommend Run Loop"
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):
self.ReportServiceStatus(win32service.SERVICE_RUNNING)
self.start_task()
win32event.WaitForSingleObject(self.hWaitStop, win32event.INFINITE)
if __name__ == '__main__':
if len(sys.argv) == 1:
try:
servicemanager.Initialize()
servicemanager.PrepareToHostSingle(StockRecommendRunLoop)
servicemanager.StartServiceCtrlDispatcher()
except win32service.error, details:
if details[0] == winerror.ERROR_FAILED_SERVICE_CONTROLLER_CONNECT:
win32serviceutil.usage()
else:
win32serviceutil.HandleCommandLine(StockRecommendRunLoop)
Reference:
Can't start Windows service written in Python (win32serviceutil)
Python Windows Service的方式运行