1

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.

2
  • how are you getting the information about the user stopping it (a KeyListener)? Commented Apr 18, 2012 at 1:11
  • OP says he's not using any UI/GUI, so it can't be that. Commented Apr 18, 2012 at 1:12

2 Answers 2

3

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 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:

  • running your worker task in a separate thread and waiting for a command(s) at the terminal to halt (or other action) that thread - this is what I'd try first, and it would be very educational for you to do this
  • monitor a file system looking for the presence/absence of a file (lame, but it works with minimal code)
  • listening to ports for messages, an HTTP port of a web server is usually the weapon of choice, but we're starting to get a bit heavier on the server side
  • monitoring a JMS queue for messages - we're in Java EE space now with still more heaviness
  • any other "change in state" you care to implement

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):

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"
}
Sign up to request clarification or add additional context in comments.

6 Comments

Out of curiousity, how would you do what the OP wants if the termination had to be by typing something and not via CTRL-C? Could something like this work?: Spawn a thread to do the real work of the program. In that thread's main loop it checks a "should I quit yet?" flag. The main thread will just sit around taking normal, blocking, console input and checking to see if the user typed the magic string. If he did, it sets the "should I quit flag" and then the next time the computation thread checks the flag it can exit and print out what it wants?
ctrl + c would actually be fine. However, I'm hoping that the rest of the program would execute. After the timer, it takes how long the timer has been running and asks for a value (like a price). So timer ran for 4 hours and pay is $8 an hour. Total is $32. I don't want to terminate the entire thing. And I appreciate the wicked fast response.
@Bohemian I'm not exactly great at coding. Do you think you'd be able to give me an example of what it would look like in the main method? That's easiest for me. If not, then show that.
@TylerMontney sure - give me a little while (kinda busy right now).
@Bohemian Perfect! Now my next step will be to create some if/else statements to convert the hours into exact hours, minutes, and seconds. Not like it's totally necessary, but it will be nice to see the time in that format. Thanks again.
|
0

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.

1 Comment

I'm not sure how to implement Timer. I've read about it but couldn't really get it to work as I'm only good at writing strictly in the main method.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.