joseluisbz
joseluisbz

Reputation: 1648

How to find out if Tomcat has stopped running with batch

I looked for an answer to this question, but couldn't find it.

This is my code restart.bat. I need to check if Tomcat has stopped before I can restart. Right now the script doesn't wait for Tomcat.

@echo off
    set "CATALINA_HOME=C:\DIR\Tomcat"
    set "STOP=%CATALINA_HOME%\bin\shutdown.bat"
    set "START=%CATALINA_HOME%\bin\startup.bat"
@echo on
    call %STOP%
    TIMEOUT /T 2

Rem trying to wait Tomcat Stop
Rem How to know it?

    call %START%
    TIMEOUT /T 2

Tomcat is running and able to answer requests when we can read in the catalina.YYYY-MM-DD.log file the line (message) like:

mmm dd, YYYY HH:mm: ss xM org.apache.catalina.startup.Catalina start
INFO: Server startup in 106737 ms

Tomcat has definitely stopped when we can read in the catalina.YYYY-MM-DD.log file the line (message) like:

mmm dd, YYYY HH:mm: ss xM org.apache.coyote.AbstractProtocol destroy
INFO: Destroying ProtocolHandler ["http-bio-8080"]
mmm dd, YYYY HH:mm: ss xM org.apache.coyote.AbstractProtocol destroy
INFO: Destroying ProtocolHandler ["ajp-bio-8009"]

Then I thought of another snippet running.bat script:

@echo off
    tasklist /FI "SessionName eq services" | find /I "tomcat" | find /I ".exe"> NUL
    if %errorlevel%==0 goto :run
    echo Tomcat is not running
    goto :eof
:run
    echo Tomcat is running
:eof

How to create only one script?

Upvotes: 1

Views: 3110

Answers (1)

sjoy
sjoy

Reputation: 502

This should do what you need. As you suggest, you don't need to check logs since the tomcat status in tasklist can tell you if it's running. I inserted code for a "wait" so tasklist gets checked every second until Tomcat has stopped.

@echo off
    set "CATALINA_HOME=C:\DIR\Tomcat"
    set "STOP=%CATALINA_HOME%\bin\shutdown.bat"
    set "START=%CATALINA_HOME%\bin\startup.bat"

:stop
    call %STOP%
    call :runstat
        echo Tomcat has stopped
        pause
    call %START%

:runstat
    tasklist /FI "SessionName eq services" | find /I "tomcat" | find /I ".exe"> NUL
    set err=%errorlevel%

    :: see if stopped condition is met and if yes exit 
       if %err%==1 exit /b
    :: else wait 1 second and try again
       PING 127.0.0.1 -n 60 >NUL 2>&1 || PING ::1 -n 60 >NUL 2>&1
       goto runstat

How it works: The code in label :runstat looks at tasklist errorlevel to determine whether or not Tomcat is running and exits back to the calling routine when Tomcat has stopped--errorlevel 1 is returned. Until 1 is returned, the ping inserts a one-second delay before tasklist is checked again via the goto.

(I've used this great ping method for inserting a delay for years. The time (60) is in milliseconds and can be adjusted . It's explained here: http://www.robvanderwoude.com/wait.php)

Upvotes: 1

Related Questions