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):
Runtime.getRuntime().addShutdownHook(new Thread(new Runnable() {
@Override
public void run() {
// print stuff here
}
}));
Get the user to type ctrl c at the command line to halt execution - your hook will run to print what you like as the JVM comes down.
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:
This is a minimal implementation that works using a shutdown hook (start on the command line and press ctrl c to end and run the calculation code):
public static void main(String[] args) throws Exception {
final long start = System.currentTimeMillis();
Runtime.getRuntime().addShutdownHook(new Thread(new Runnable() {
@Override
public void run() {
double hours = (System.currentTimeMillis() - start) / 3600000d;
System.out.println("Please enter the hourly rate");
double hourlyRate = new Scanner(System.in).nextDouble();
System.out.format("Program ran for %01.3f hours and cost $%02.2f", hours, hourlyRate * hours);
}
}));
Thread.sleep(Long.MAX_VALUE); // Sleep "forever"
}
Could you start a Thread with daemon true, and then read a line in System.input, then interrupt the thread. java.util.Timer
is possible too.
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.