Beto Neto
Beto Neto

Reputation: 4112

How to auto restart a java application using Procrun by Exit Code

My application has a self-update feature.

It downloads a new version by itself, and when this occurrs at the end of the download process the JVM exits with code 2.

Is possible to configure the Procrun to auto-restart the service if the exit code 2 occurrs ?

Upvotes: 2

Views: 1156

Answers (1)

Beto Neto
Beto Neto

Reputation: 4112

I solved using another tool for running my application as a service: NSSM

With it, I register a parameter to NSSM like this:

nssm install my-service-name "java -jar snapshot.jar"
nssm set my-service-name AppEvents "Start/Pre" "cmd /c copy /y my-app.jar snapshot.jar"
nssm set my-service-name AppExit Default Exit
nssm set my-service-name AppExit 2 Restart
nssm set my-service-name AppDirectory "c:\path\to\my\app"

So, this lines will:

  1. Register a windows service named my-service-name who launches a copy of my jar (java) application.
  2. Set a parameter to NSSM to copy my-app.jar to snapshot.jar before start the service.
  3. Set a parameter to NSSM to specify that, when my app terminates the default behavior is assuming that the service must stop
  4. Set a parameter to NSSM to specify that, when my app terminates with the exit code 2 it must be restarted (my java application) and the service must continue to running.
  5. Set a parameter to NSSM to specify that my app will using the current directory as c:\path\to\my\app

Another solution is creating a batch file to be on loop, like this (I called it run-app.bat):

@echo off
set java=C:\Program Files (x86)\Java\jre1.8.0_192
:start
copy /y my-app.jar snapshot.jar
if %errorlevel% equ 0 goto :run
if %errorlevel% neq 0 goto :end
:run
"%java%\bin\java.exe" -jar snapshot.jar --start
if %errorlevel% equ 2 goto :start
:end
exit /b %errorlevel%

And using the NSSM to register the service in a simple way:

nssm install my-service-name "cmd /c run-app.bat"
nssm set my-service-name AppDirectory "c:\path\to\my\app"

In this scenario, the NSSM will just launch my batch run-app.bat. The batch will stay on loop (restarting my app) while the application exits with code 2.

Upvotes: 5

Related Questions