This may sound like it’s been asked before, but it’s a bit different than the norm. I don’t want the typical (After the user has run the program, I want it to ask “would you like to go again?”). I want to start a process (by typing a certain string which I’ve accomplished) and have it run for an infinite amount of time until the user stops it. There’s no way of knowing how long it will run. This program happens to be a timer. So I need it to calculate how long it’s been running, be able to be stopped at any given moment by the user, and print out how long it ran.
As of now, I’m not using any UI/GUI. Keeping it as simple as possible.
Set up a shutdown hook (code that runs when the JVM is halting):
Get the user to type ctrlc at the command line to halt execution – your hook will run to print what you like as the JVM comes down.
Edit:
The above is brutal but simple, however if you didn’t want to terminate the whole JVM, you’re getting into the realm of "server events" to drive behaviour, which can take many forms to cause an action:
Edit 2:
This is a minimal implementation that works using a shutdown hook (start on the command line and press ctrlc to end and run the calculation code):