1

My problem is: I have two blocks of code.. One block I execute only if the Timer reached 10seconds.. so I invoke the TimerTask with the piece of code.. The other block of code I execute only if I don't get into the TimerTask function.. (the run() function).. Is there a way to know if a TimerTask has completed its execution, like returning a Boolean variable, for example? I'm programming in Java.

I tried:

TimerTask emd = new EsperaMensagemDigitada(outgoing, incoming);
timer.schedule(emd, 10000);
if(emd.cancel() == true){
   messageOut = userInput.readLine();               
   outgoing.println(messageOut + "            [Sua vez]");
   System.out.println("Aguardando resposta...");
   outgoing.flush();    
}

but it seems that it will ALWAYS execute the code inside the if clausure.. so I dind't resolve my problem yet..

The other part of this problem is that I have this code:

messageOut = userInput.readLine();

I want, if the user doesn't enter any message for 10 seconds I print a default message, if he entered a message until 10 seconds, I print his message. The problem is I get stuck on userInput.readLine(), waiting for an entry..

2 Answers2

1

You can attempt to cancel the TimerTask using TimerTask.cancel() which returns boolean value that is true if and only if the cancel resulted in the scheduled task not running and false otherwise (meaning the task has already been fired and may be in progress or already done with the run() method)

Dev
  • 11,919
  • 3
  • 40
  • 53
1

I think you should rather use FutureTask with ScheduledExecutorService for this purpose. FutureTask has an isDone method to check if it is completed. Since TimerTask implements Runnable, you can wrap your task quite easily in a FutureTask:

FutureTask<?> futureTask = new FutureTask<Void>(timerTask, null);
ScheduledExecutorService scheduler = Executors.newScheduledThreadPool(1);
scheduler.schedule(futureTask, 10, TimeUnit.SECONDS);
if (futureTask.isDone()) {
    // ...
}
Katona
  • 4,816
  • 23
  • 27
  • I still don't get it.. :( My problem is that I have this code: messageOut = userInput.readLine(); I want, if the user doesn't enter any message for 10 seconds I print a default message, if he entered a message until 10 seconds, I print his message. The problem is I get stuck on userInput.readLine(), waiting for an entry.. – Christiane Okamoto Aug 25 '13 at 19:13
  • @ChristianeOkamoto I misunderstood the question: check [this](http://stackoverflow.com/questions/804951/is-it-possible-to-read-from-a-inputstream-with-a-timeout) question then – Katona Aug 25 '13 at 21:05