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:
-
Create the start and the stop script of your application. Put it on some directory, in our example is:
- Start Script:
/usr/local/bin/myapp-start.sh
- Stop Script:
/usr/local/bin/myapp-stop.sh
Each one will provide the instructions to run/stop the app. For instance the
myapp-start.sh
content can be as simple as the following:#!/bin/bash java -jar myapp.jar
For the stop script it can be something like this:
#!/bin/bash # Grabs and kill a process from the pidlist that has the word myapp pid=`ps aux | grep myapp | awk '{print $2}'` kill -9 $pid
- Start Script:
-
Create the following script (
myscript
) and put it on/etc/init.d
./etc/init.d/myscript
content:#!/bin/bash # MyApp # # description: bla bla case $1 in start) /bin/bash /usr/local/bin/myapp-start.sh ;; stop) /bin/bash /usr/local/bin/myapp-stop.sh ;; restart) /bin/bash /usr/local/bin/myapp-stop.sh /bin/bash /usr/local/bin/myapp-start.sh ;; esac exit 0
-
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.
Yes! It is possible. :) Upstart is the way to go to make sure the service stays running. It has five packages, all installed by default:
- Upstart init daemon and initctl utility
- upstart-logd provides the logd daemon and job definition file for logd service
- upstart-compat-sysv provides job definition files for the rc tasks and the reboot, runlevel, shutdown, and telinit tools that provide compatibility with SysVinit
- startup-tasks provides job definition files for system startup tasks
- system-services provides job definition files for tty services
The learning is very enjoyable and well worth it. Upstart has a website: http://upstart.ubuntu.com/
3 quick suggestions...
-
Create a Start script in
/etc/rc3.d
(multiuser console mode) with corresponding Kill scripts in/etc/rc.0
and/etc/rc6.d
to kill your Java program in a controlled way when the system powers down (runevel 0) or reboots (runlevel 6) See An introduction to Runlevels.You might be able to start your Java app in runlevel 2 (rc2.d) but, as a crawler, it will need TCP/IP. So make sure your networking service is available/started in your runlevel 2 beforehand. Networking is definitely up in runlevel 3.
/etc/init.d
contains all the actual start/kill scripts./etc/rcN.d
directories just contain links to them, prefixed with S or K to start or kill them respectively, per runlevel N. A process run by
crond
should persist between logouts. Maybe add it to your crontab.-
A process run with
nohup
should also persist. See nohup: run a command even after you logout.$ nohup java -jar myapp.jar &
By default,
myapp.jar
's standard output will go to a file named./nohup.out
, or$HOME/nohup.out
if the former isn't writeable.