Read from stdin but unable to know when to stop

97 Views Asked by At

I am running some commnads on commmand prompt. I am waiting for the last command's output to complete. I have to read the output and perform the operation. My command's output is very dynamic and I can not predict when I can stop reading.

I am having issues that I dont know when to stop reading. If suppose I keep the while read(), then my last command output is not ending with new line. Is there any mechenism which can tell me if there has been no activity on stdin for last 5mins, then I get some alert??

1

There are 1 best solutions below

1
On

The approach I took was to create a class implementing Runnable which monitors the value of a shared AtomicInteger flag. This InputRunnable class sleeps for 5 minutes (300000 ms) and then wakes up to check whether the value has been set by the main method. If the user has entered at least one input in the last 5 minutes, then the flag would be set to 1, and InputRunnable will continue execution. If the user has not entered an input in the last 5 minutes, then the thread will call System.exit() which will terminate the entire application.

public class InputRunnable implements Runnable {
    private AtomicInteger count;

    public InputRunnable(AtomicInteger count) {
        this.count = count;
    }

    public void run() {
        do {
            try {
                Thread.sleep(300000);               // sleep for 5 minutes
            } catch (InterruptedException e) {
                // log error
            }

            if (count.decrementAndGet() < 0) {      // check if user input occurred
                System.exit(0);                     // if not kill application
            }
        } while(true);
    }
}

public class MainThreadClass {
    public static void main(String args[]) {
        AtomicInteger count = new AtomicInteger(0);
        InputRunnable inputRunnable = new InputRunnable(count);
        Thread t = new Thread(inputRunnable);
        t.start();

        while (true) {
            System.out.println("Enter a number:");
            Scanner in = new Scanner(System.in);
            int num = in.nextInt();                 // scan for user input

            count.set(1);
        }
    }
}

I tested this code locally and it appears to be working, but please let me know if you have any issues getting it to run on your system.