0

I am executing a simple command where user gives the options(args) and I made a logic to get the args in Java program in which I am using wait() for particular time so that command will take that much minimum time to execute.I am saving some data in a file after that.

Within this time if the user wants to end the process ,should be able to stop the process smoothly by giving input like "exit" in the command prompt.

Please help.

AndroidCrazy
  • 334
  • 8
  • 23

1 Answers1

1

The standard way of interrupting a command line program is by adding a Ctrl-C handler to your app:

Runtime.getRuntime().addShutdownHook(new Thread() {
  public void run() { 
    // cleanup logic here
  }
});

See this question for more details.

Since you insist. Here is an implementation when commands are executed in background threads. I hope the complexity of this example will deter you from implementing it:

import java.util.Scanner;
import java.util.concurrent.ExecutorService;
import java.util.concurrent.Executors;
import java.util.concurrent.TimeUnit;

public class Shell {
  private static final int NUM_PARALLEL_COMMANDS = 5;
  private static final int SLEEP_DURATION = 1000;

  public static void main(String[] args) throws InterruptedException {
    ExecutorService executor = 
        Executors.newFixedThreadPool(NUM_PARALLEL_COMMANDS);
    try (Scanner scanner = new Scanner(System.in)) {
      String command = null;     
      int counter = 0;
      do {
        command = scanner.nextLine();
        switch (command) {
          case "DoStuff":
            executor.submit(NewDoStuffCommand(++counter));
            break;
        }
      } while (!command.equals("exit"));
    }

    executor.shutdownNow();
    executor.awaitTermination(1, TimeUnit.SECONDS);
  }

  private static Runnable NewDoStuffCommand(final int counter) {
    return new Runnable() {
      @Override 
      public void run() {
        try {
          for (int i = 0; i < 10; i++) {
            System.out.println(counter + ": Doing time consuming things...");
            Thread.sleep(SLEEP_DURATION);
          }
          System.out.println(counter + ": Finished.");
        } catch (InterruptedException e) {
          System.out.println(counter + ": Command interrupted :(");
          // do cleanup
          Thread.currentThread().interrupt();
        }
      }
    };
  }
}
Community
  • 1
  • 1
LeffeBrune
  • 3,441
  • 1
  • 23
  • 36
  • i want to send stop signal when user inputs "exit"even before command finishes execution,How can i do that? – AndroidCrazy Nov 13 '14 at 13:37
  • 1
    You'll need to run multiple threads, which will make your code unnecessarily complicated. Exactly the reason why all good command line utils rely on BREAK command aka Ctrl-C. – LeffeBrune Nov 13 '14 at 13:49