Okay, so I have spent some time looking around but have not been able to find clear solution. I posted a separate question earlier but that is little bit different problem.
Problem: I want to poll for a condition to happen at periodically. If that condition is still false, again reschedule. If true, stop the scheduling. But I also want to wait only for some definitive amount of time. Here is what I wrote
final ScheduledExecutorService service = Executors.newScheduledThreadPool(1);
final Future<?> future = service.schedule(new Runnable() {
@Override
public void run() {
if (conditionFalse()) {
System.out.println("its false. Rescheduling");
service.schedule(this, 2, TimeUnit.SECONDS);
} else {
System.out.println("true. Exiting");
}
}
}, 2, TimeUnit.SECONDS);
//Wait only for 5 seconds
future.get(5, TimeUnit.SECONDS); // does not work
//does not work either
service.schedule(new Runnable() {
@Override
public void run() {
future.cancel(true);
}
}, 5, TimeUnit.SECONDS);
This keeps rescheduling itself until condition is met. Any suggestions on why it's not working? How do I wait only for 5 seconds and then stop the task execution?