terminate java program

How to terminate the execution of a process after some time in Linux

Suppose that you have to execute a Java program which is fairly unstable and sometimes hangs on and never terminates. Is there a simple way to make it terminate (actually by killing the process) after some time? Yes, of course. There is always a way for such things. Ways for everything do not exist though.

So, let's say you have a program.jar to execute but you want to kill its process after 5 minutes in case it does not terminate. A very easy way to do this is the following:

#!/bin/bash

# here you set the time you want to wait before killing the process
time=5m

# then you run your program in the background
java -jar program.jar &

# you are waiting for the time you have set
sleep $time

# some printing - for fun
termination="\nTerminating the process...!!\n"
echo -e $termination

# and now you are about to kill it
kill %1

You can create a script.sh file, just copy paste the code above, and then run the script.sh file (by using the command > sh script.sh).

Syndicate content