Kill all Java processes which have been running for more than two hours

On linux OS, how can I kill all Java processes that have been running on a server for more than 2 hours? Currently I'm using pkill -f 'java -jar' once every twenty four hours to kill processes but this also kills any current running process.
Who is Participating?
Gerwin Jansen, EE MVEConnect With a Mentor Topic Advisor Commented:
Try this:

ps -eo pid,lstart,command | grep java | grep -v grep

It will give you a date/time sorted list of java processes, change 'java' to something else if you need a different filter.

Don't know how long your list typically is but you could add something like '| head -5' to get a list of the 5 oldest processes that you can kill this way:

kill $(ps -eo pid,lstart,command | grep java | grep -v grep | head -5 | awk '{print $1}')

You could also filter on the 2nd column (with awk maybe) and search for the 2 hour processes.
That sounds like what you're asking is not the real problem. Why are there processes around that shouldn't be?
SheppardDigitalAuthor Commented:
That's something we need to look at, but in the meantime we need to apply a temporary solution until we have free resources to investigate the main cause of the issue.
I could possibly give you a free consultation on this.
Question has a verified solution.

Are you are experiencing a similar issue? Get a personalized answer when you ask a related question.

Have a better answer? Share it in a comment.

All Courses

From novice to tech pro — start learning today.