原料:Jenkins+tornado+flask+window服务+批处理
原理:将tornado建成window服务,使用Jenkins调用重启tornado服务的方式完成flask的自动构建
注意:要先把pythonservice kill掉才能重启服务
代码:1.flask应用代码:自备
2.tornado集成flask代码:详见创建服务代码中
3.创建服务代码:
1 #-*- coding:utf-8 -*- 2 import win32serviceutil 3 import win32service 4 import win32event 5 6 class PythonService(win32serviceutil.ServiceFramework): 7 8 #服务名 9 _svc_name_ = "TornadoService" 10 #服务显示名称 11 _svc_display_name_ = "Tornado Najie Service" 12 #服务描述 13 _svc_description_ = "Tornado Najie Service" 14 15 def __init__(self, args): 16 win32serviceutil.ServiceFramework.__init__(self, args) 17 self.hWaitStop = win32event.CreateEvent(None, 0, 0, None) 18 self.logger = self._getLogger() 19 self.isAlive = True 20 from tornado.wsgi import WSGIContainer #tornado集成flask 21 from tornado.httpserver import HTTPServer 22 from tornado.ioloop import IOLoop 23 from najie import app 24 http_server = HTTPServer(WSGIContainer(app)) 25 http_server.listen(8016) #flask默认的端口 26 IOLoop.instance().start() 27 28 def _getLogger(self): 29 import logging 30 import os 31 import inspect 32 33 logger = logging.getLogger('[PythonService]') 34 35 this_file = inspect.getfile(inspect.currentframe()) 36 dirpath = os.path.abspath(os.path.dirname(this_file)) 37 handler = logging.FileHandler(os.path.join(dirpath, "service.log")) 38 39 formatter = logging.Formatter('%(asctime)s %(name)-12s %(levelname)-8s %(message)s') 40 handler.setFormatter(formatter) 41 42 logger.addHandler(handler) 43 logger.setLevel(logging.INFO) 44 45 return logger 46 47 def SvcDoRun(self): 48 import time 49 self.logger.error("svc do run....") 50 while self.isAlive: 51 self.logger.error("I am alive.") 52 time.sleep(1) 53 # 等待服务被停止 54 #win32event.WaitForSingleObject(self.hWaitStop, win32event.INFINITE) 55 56 def SvcStop(self): 57 # 先告诉SCM停止这个过程 58 self.logger.error("svc do stop....") 59 self.ReportServiceStatus(win32service.SERVICE_STOP_PENDING) 60 # 设置事件 61 win32event.SetEvent(self.hWaitStop) 62 self.isAlive = False 63 64 if __name__=='__main__': 65 win32serviceutil.HandleCommandLine(PythonService)
4.创建服务命令:
安装服务 python PythonService.py install 让服务自动启动 python PythonService.py --startup auto install 启动服务 python PythonService.py start 重启服务 python PythonService.py restart 停止服务 python PythonService.py stop 删除/卸载服务 python PythonService.py remove
5.Jenkins批处理命令:
start E:JenkinsworkspaceNajieayeshead_ctmodules\_6_usingkillpython.bat
killpython.bat内容如下:
1 tasklist|findstr /i pythonservice.exe && taskkill /f /im pythonservice.exe
第二条命令:
1 start E:JenkinsworkspaceNajieayeshead_ctmodules\_6_using
estart.bat
restart.bat内容如下:
1 @echo off 2 echo 停止Najie 3 net stop TornadoService 4 echo 重新启动Najie 5 net start TornadoService 6 echo 完成!!!! 7 pause
完成的效果就是:不必Jenkins构建完再手动重启tornado了。