在日常开发或者测试过程中,如果项目有升级的情况,需要手动部署并且重启tomcat,现通过python编写了一个监听文件的变化来自动重启的脚本,前提是需要将下面文件restart.bat放在tomcat的bin目录下,涉及到两个文件:
watch_files.py内容如下:
#! /usr/bin/env python
# -*- coding: utf-8 -*-
# 打包 D:\software\Python\Scripts\pyinstaller.exe -Fw watch_files.py
from __future__ import print_function
import os
from datetime import datetime
import time
from threading import Timer
from watchdog.events import FileSystemEventHandler
from watchdog.observers import Observer
WATCH_PATH = 'D:\\software\\apache-tomcat-7.0.63\\webapps' # 监控目录
TOMCAT_PATH = 'D:\\software\\apache-tomcat-7.0.63\\bin\\restart.bat' #TOMCAT目录
STARTING = False
# 监控文件变更
class FileMonitorHandler(FileSystemEventHandler):
def __init__(self, **kwargs):
super(FileMonitorHandler, self).__init__(**kwargs)
# 监控目录
self._watch_path = WATCH_PATH
# 重写文件改变函数,文件改变都会触发文件夹变化
def on_modified(self, event):
global STARTING
if not event.is_directory: # 文件改变都会触发文件夹变化
file_path = event.src_path
print("项目文件已变更: %s " % file_path)
STARTING = True
# 调度任务
def timedTask():
Timer(5, dowork, ()).start()
# 任务工作
def dowork():
while True:
global STARTING
print('dowork:' + str(datetime.now()))
if STARTING:
print('重新启动项目:' + str(datetime.now()))
os.system('chcp 65001')
os.system(TOMCAT_PATH)
STARTING = False
time.sleep(5)
# 主函数
if __name__ == "__main__":
event_handler = FileMonitorHandler()
observer = Observer()
observer.schedule(event_handler, path=WATCH_PATH, recursive=True) # recursive递归的
print('已启动...')
timedTask()
observer.start()
observer.join()
restart.bat内容如下:
@echo off
chcp 65001
echo %~dp0
set current_dir=%~dp0
echo stopping...
ping /n 1 /w 1000 1.0.0.1>nul
::echo %current_dir%shutdown.bat
cd %current_dir%
call %current_dir%shutdown.bat
echo restarting...
ping /n 1 /w 2000 1.0.0.1>nul
echo %current_dir%startup.bat
cd %current_dir%
call %current_dir%startup.bat
echo open browser...
ping /n 1 /w 2000 1.0.0.1>nul
start chrome.exe http://localhost:8080
本文暂时没有评论,来添加一个吧(●'◡'●)