How to make a jar file run on startup & and when you log out?

Here’s a easy way to do that using SysVInit. Instructions:

  1. Create the start and the stop script of your application. Put it on some directory, in our example is:
    • Start Script: /usr/local/bin/
    • Stop Script: /usr/local/bin/

    Each one will provide the instructions to run/stop the app. For instance the myapp-start.shcontent can be as simple as the following:

    java -jar myapp.jar 

    For the stop script it can be something like this:

    # Grabs and kill a process from the pidlist that has the word myapp
    pid=`ps aux | grep myapp | awk '{print $2}'`
    kill -9 $pid
  2. Create the following script (myscript) and put it on /etc/init.d.

    /etc/init.d/myscript content:

    # MyApp
    # description: bla bla
    case $1 in
            /bin/bash /usr/local/bin/
            /bin/bash /usr/local/bin/
            /bin/bash /usr/local/bin/
            /bin/bash /usr/local/bin/
    exit 0
  3. Put the script to start with the system (using SysV). Just run the following command (as root):
    update-rc.d myscript defaults 

PS: I know that Upstart is great and bla bla, but I preffer the old SysV init system.