Linux запуск java приложения при запуске

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

Any ideas? Can someone point me in the right direction?

Just looking for the simplest solution.

7 Answers 7

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/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 ''` kill -9 $pid 
#!/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 
update-rc.d myscript defaults 

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

But how do the system will know what parameter will use? How to set to be the «start». Tried here and it did not work.

Also, even after doing the 3 steps, my jar is not running on startup. Are you sure if we have to change permissions, or path or something like that?

This worked for me, thank you. But I had to make the last script (‘myscipt’ in your example) executable with this command: chmod 755 /etc/init.d/myscript . Otherwise update-rc.d command couldn’t execute it.

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/

From the Upstart website, as of 2019: «Project is in maintaince mode only. No new features are being developed and the general advice would be to move over to another minimal init system or systemd»

  1. 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.
  2. A process run by crond should persist between logouts. Maybe add it to your crontab.
  3. A process run with nohup should also persist. See nohup: run a command even after you logout.

Источник

Как запустить приложение Java при запуске Ubuntu Linux

В идеале вы должны создать оболочку службы для приложения Java, а затем сделать этот сервис работает на примере запуска здесь.

использование
sudo update-rc.d mytestserv defaults запускает вашу сервисную оболочку при запуске на Ubuntu

Что делать, если я не изменю PID_PATH_NAME = / tmp / MyService-pid в вашей программе. Если я оставлю все как есть. Будет все в порядке

Еще один глупый вопрос. Извините, сэр, я очень новичок в Linux. Как выйти из этой команды sudo vi /etc/init.d/mytestserv после вставки скрипта и выполнить следующую команду, т.е. sudo chmod + x / etc / init .d / mytestserv

ты имеешь ввиду выход из редактора vi !! ?? нажмите «ESC +: wq +« INTRO »для выхода. Если вы хотите перезагрузить компьютер, попробуйте« sudo reboot now »или« sudo reboot »

Понял, сэр . Еще одна вещь, если мой сервис находится в запущенном режиме и через некоторое время я перезагружаю свою систему Linux, тогда мой сервис будет автоматически запущен. Я прав?

Итак, вам нужно сделать две вещи:

Сначала создайте небольшой сценарий оболочки, чтобы запустить вашу программу java с терминала. Поскольку вы упаковали в виде банки, посмотрите на это, в частности на раздел JAR Files as Applications .

Этого может быть достаточно: (хотя вы хотите использовать полный путь к Java)

#!/bin/bash java -jar path_to_jar_file 

Вы должны иметь возможность запускать скрипт и успешно запускать свою программу.

Как только вы его начинаете с скрипта, вы можете использовать стандартные инструменты linux для запуска скрипта. Либо добавив его в /etc/rc.local , либо когда вы используете Ubuntu, используйте update-rc.d, чтобы запустить его при загрузке. См. Здесь очень простой пример использования update-rc.d

Источник

Linux start-up script for java application

Can anyone let me know how to create script and implement this process automatically while we restart our computer? In windows we use services but how about linux? Can u provide to me the script and step to do that since i am really new in Linux. Linux : RHat, Ubuntu Thanks

6 Answers 6

I would start with this template for a startup script rename the SCRIPT_HOME to proper path and call this file without any extensions, then in SSH run this command.

Note the javaserver in the chkconfig is how you called the file below, (no extensions or it wont work).

#!/bin/bash # # javaserver: Startup script for Any Server Application. # # chkconfig: 35 80 05 # description: Startup script for Any Server Application. SCRIPT_HOME=/var/java_server; export SCRIPT_HOME start() < echo -n "Starting Java Server: " $SCRIPT_HOME/run.sh start sleep 2 echo "done" >stop() < echo -n "Stopping Java Server: " $SCRIPT_HOME/run.sh stop echo "done" ># See how we were called. case "$1" in start) start ;; stop) stop ;; restart) stop start ;; *) echo $"Usage: javaserver " exit esac 

Now here is the script the run.sh (this can be used instead of the template but I find it easier to make the template script small and unchangeable link to my main script so I never have to touch it again.

The script below is one of a very few scripts I found that actually can restart a java program without turning off all the java programs you currently have running, this one only targets the program it opened in the first place so it will never make any mistakes, never had it fail on me, run on user root no problem.
Runs your program in the background forever too (no need to keep SSH opened).

#!/bin/bash # # chkconfig: 345 99 05 # description: Java deamon script # # A non-SUSE Linux start/stop script for Java daemons. # # Set this to your Java installation JAVA_HOME=/usr/bin/ scriptFile=$(readlink -fn $(type -p $0)) # the absolute, dereferenced path of this script file scriptDir=$(dirname $scriptFile) # absolute path of the script directory serviceNameLo="javaserver" # service name with the first letter in lowercase serviceName="JavaServer" # service name serviceUser="root" # OS user name for the service serviceGroup="root" # OS group name for the service applDir="/var/java_server" # home directory of the service application serviceUserHome="/home/$serviceUser" # home directory of the service user serviceLogFile="/var/log/$serviceNameLo.log" # log file for StdOut/StdErr maxShutdownTime=15 # maximum number of seconds to wait for the daemon to terminate normally pidFile="/var/run/$serviceNameLo.pid" # name of PID file (PID = process ID number) javaCommand="java" # name of the Java launcher without the path javaArgs="MyJavaAppClass" # arguments for Java launcher javaCommandLine="$JAVA_HOME$javaCommand $javaArgs" # command line to start the Java service application javaCommandLineKeyword="MyJavaAppClass" # a keyword that occurs on the commandline, used to detect an already running service process and to distinguish it from others # Makes the file $1 writable by the group $serviceGroup. function makeFileWritable < local filename="$1" touch $filename || return 1 chgrp $serviceGroup $filename || return 1 chmod g+w $filename || return 1 return 0; ># Returns 0 if the process with PID $1 is running. function checkProcessIsRunning < local pid="$1" if [ -z "$pid" -o "$pid" == " " ]; then return 1; fi if [ ! -e /proc/$pid ]; then return 1; fi return 0; ># Returns 0 if the process with PID $1 is our Java service process. function checkProcessIsOurService < local pid="$1" if [ "$(ps -p $pid --no-headers -o comm)" != "$javaCommand" ]; then return 1; fi grep -q --binary -F "$javaCommandLineKeyword" /proc/$pid/cmdline if [ $? -ne 0 ]; then return 1; fi return 0; ># Returns 0 when the service is running and sets the variable $pid to the PID. function getServicePID < if [ ! -f $pidFile ]; then return 1; fi pid="$(<$pidFile)" checkProcessIsRunning $pid || return 1 checkProcessIsOurService $pid || return 1 return 0; >function startServiceProcess < cd $applDir || return 1 rm -f $pidFile makeFileWritable $pidFile || return 1 makeFileWritable $serviceLogFile || return 1 cmd="nohup $javaCommandLine >>$serviceLogFile 2>&1 & echo \$! >$pidFile" # Don't forget to add -H so the HOME environment variable will be set correctly. #sudo -u $serviceUser -H $SHELL -c "$cmd" || return 1 su --session-command="$javaCommandLine >>$serviceLogFile 2>&1 & echo \$! >$pidFile" $serviceUser || return 1 sleep 0.1 pid="$( <$pidFile)" if checkProcessIsRunning $pid; then :; else echo -ne "\n$serviceName start failed, see logfile." return 1 fi return 0; >function stopServiceProcess < kill $pid || return 1 for ((i=0; ifunction startService < getServicePID if [ $? -eq 0 ]; then echo -n "$serviceName is already running"; RETVAL=0; return 0; fi echo -n "Starting $serviceName " startServiceProcess if [ $? -ne 0 ]; then RETVAL=1; echo "failed"; return 1; fi echo "started PID=$pid" RETVAL=0 return 0; >function stopService < getServicePID if [ $? -ne 0 ]; then echo -n "$serviceName is not running"; RETVAL=0; echo ""; return 0; fi echo -n "Stopping $serviceName " stopServiceProcess if [ $? -ne 0 ]; then RETVAL=1; echo "failed"; return 1; fi echo "stopped PID=$pid" RETVAL=0 return 0; >function checkServiceStatus < echo -n "Checking for $serviceName: " if getServicePID; then echo "running PID=$pid" RETVAL=0 else echo "stopped" RETVAL=3 fi return 0; >function main < RETVAL=0 case "$1" in start) # starts the Java program as a Linux service startService ;; stop) # stops the Java program service stopService ;; restart) # stops and restarts the service stopService && startService ;; status) # displays the service status checkServiceStatus ;; *) echo "Usage: $0 " exit 1 ;; esac exit $RETVAL > main $1 

Источник

How to run Java application on startup of Ubuntu Linux

Ideally you should create a service wrapper for your java application and then make this service run on startup example here.

Use
sudo update-rc.d mytestserv defaults to run your service wrapper on startup on Ubuntu

What if i wont change PID_PATH_NAME=/tmp/MyService-pid in your program.If i let it be as it is.Will it be OK

one More Silly question.Am sorry sir i am very novice to Linux ..How to come out of this command sudo vi /etc/init.d/mytestserv after pasting the script and execute next command i.e sudo chmod +x /etc/init.d/mytestserv

you mean getting out the vi editor. press «ESC + :wq + «INTRO» to exit. If you mean to reboot the machine try «sudo reboot now» or «sudo reboot»

Got it sir..One More thing if my service is in started Mode and after some time i rebooted my Linux System then My Service will automatically be Started.Am i Right?

So two things you’ll need to do:

First create a small shell script to start your java program from a terminal. As you have packaged as a jar have a look at this, specifically the JAR Files as Applications section.

This may be sufficient: (although you’ll want to use the full path to Java)

#!/bin/bash java -jar path_to_jar_file 

You should be able to run your script and successfully start your program.

Once you’ve got it starting from a script you can use standard linux tools to start the script. Either putting it in /etc/rc.local , or as you’re using Ubuntu, use update-rc.d to start it on boot. See here for a very simple example of using update-rc.d

Источник

Читайте также:  Linux update link file
Оцените статью
Adblock
detector