Set timeout for user input

Can I set a timer for user input? Wait 10 seconds - perform the following operation, etc. I mean for example

//wait several seconds{ String s = new BufferedReader(new InputStreamReader(System.in)).readLine(); //wait server seconds} //next operation and etc. 
+7
source share
3 answers

Not right out of the box, no. Normally, Reader aborts the read () call only when another thread closes the main thread, or you reach the end of the input.

Since read () is not so interruptible, this becomes a parallel programming problem. A thread that knows about the timeout should be able to interrupt a thread that is trying to read input.

In fact, the read stream will have to query the Reader ready () method, and not be blocked in read () when there is nothing to read. If you put this polling and waiting operation in java.util.concurrent.Future, then call the get () method of Future with a timeout.

This article is detailed: http://www.javaspecialists.eu/archive/Issue153.html

+6
source

A slightly easier way to do this than Benjamin Cox's answer is to do something like

 int x = 2; // wait 2 seconds at most BufferedReader in = new BufferedReader(new InputStreamReader(System.in)); long startTime = System.currentTimeMillis(); while ((System.currentTimeMillis() - startTime) < x * 1000 && !in.ready()) { } if (in.ready()) { System.out.println("You entered: " + in.readLine()); } else { System.out.println("You did not enter data"); } 

This, however, will consume more resources than its solution.

+13
source
  BufferedReader inputInt = new BufferedReader(new InputStreamReader(System.in)); Robot enterKey = new Robot(); TimerTask task = new TimerTask() { public void run() { enterKey.keyPress(KeyEvent.VK_ENTER); } }; Timer timer = new Timer(); timer.schedule(task, 30 * 1000); userInputanswer = inputInt.read(); timer.cancel(); 
0
source

Source: https://habr.com/ru/post/912668/


All Articles