@echo off&setlocal enabledelayedexpansion @rem (start /min cmd.exe /c %0 :&exit) start /min title Tomcat 重啟腳本%1 cd ..\ set CATALINA_HOME=%cd% set STR_TASK=%1 set JAVA_HOME=%CATALINA_HOME%\bin\jdk1.7.0_55 cd /D %CATALINA_HOME%\bin call %CATALINA_HOME%\bin\shutdown.bat ping -n 3 localhost >nul wmic process where name="java.exe" get processid,commandline |findstr /i %STR_TASK% ># for /f "delims=*" %%i in (#) do ( set var=%%i set var=!var:start= #! for /f "tokens=3 delims=#" %%a in ("!var!") do (set tomcatpid=%%a) ) del # >nul if defined tomcatpid taskkill /pid !tomcatpid! ping -n 3 localhost >nul call %CATALINA_HOME%\bin\startup.bat taskkill /im cmd.exe
由於windows的任務不好鎖定,所以執行的時候,需要傳入tomcat的主目錄的名稱用來鎖定進程號,保證運行的tomcat中沒有重復的文件名。
下面是我代碼的調用示例
String cmdcommand = ""; String osname = System.getProperties().getProperty("os.name").toLowerCase(); File partfile = new File(new File(ServerDirUtils.getServerRoot()).getParent()); String rootdirpath = partfile.getParent(); String rootname = partfile.getParentFile().getName(); if(!osname.toLowerCase().contains("windows")){ String rootPath = rootdirpath +File.separator+"bin"+File.separator+"restart.sh"; cmdcommand = "sh "+rootPath+ " "+rootname; }else{ String rootPath = rootdirpath+File.separator+"bin"+File.separator+"restart.bat"; cmdcommand = "cmd /c start "+rootPath+" "+rootname; } logger.error("執行的命令為:"+cmdcommand); try { Runtime.getRuntime().exec(cmdcommand); } catch (IOException e) { // TODO Auto-generated catch block e.printStackTrace(); }
如假如我的tomcat的目錄為D:\zhk\apache-tomcat-8.5.39
那命令的組成為:
cmdcommand = "cmd /c start 【你的重啟bat的所在的位置,建議放在bin目錄下】 apache-tomcat-8.5.39