I am confused with the following
I know, if I use the schedule
method from the ScheduledThreadPoolExecutor
class:
ScheduledFuture<?> scheduledFuture =
scheduledThreadPoolExecutor.schedule(myClassRunnable, 5, TimeUnit.SECONDS);
I am able to retrieve later the value through
scheduledFuture.get(5, TimeUnit.SECONDS)
or scheduledFuture.get()
and should be null because the task has been executed just only once and it is completed.
And null because I am working with the shedule's Runnable
method version and not with the shedule's Callable
method version. It according with the API
Until here I am fine.
My question:
What is the purpose of ScheduledFuture
if is retrieved from the scheduleWithFixedDelay
(even from scheduleAtFixedRate
) method:
ScheduledFuture<?> scheduledFuture=
scheduledThreadPoolExecutor.scheduleWithFixedDelay(myClassRunnable, 1, 5, TimeUnit.SECONDS);
Yes, I know both fixed methods execute the same task many times until the ScheduledThreadPoolExecutor's shutdown
method is called (it must stop all the tasks scheduled).
I did a research through Google looking for some examples using ScheduledFuture
returned from scheduleWithFixedDelay
, I only found one using the cancel method, to cancel a specific task. But none working with get.
I don't know if I am wrong, but seems useless the get method if we are working with scheduleWithFixedDelay
, because if I use later:
- scheduledFuture.get() - it remains awaiting and the Runnable object remains working many times (run,complete,delay,run,etc... )
- scheduledFuture.get(32, TimeUnit.SECONDS) - always appears TimeoutException
I thought I should be able to retrieve the null value since I can use the period
argument/parameter from the scheduleWithFixedDelay
method. I mean: run the Runnable object, wait until it completes and use the scheduledFuture.get() to get the null value that confirms it has been completed, await the period of the delay time to run again the Runnable object according with the period
value etc....
Clarifications and examples are totally well welcome
Thanks in advance.
ScheduledFuture can be used to get time left before next task execution:
ScheduledFuture<?> f = Executors.newScheduledThreadPool(1).scheduleAtFixedRate(new Runnable() {
public void run() {
System.out.println("run");
}
}, 0, 10000, TimeUnit.MILLISECONDS);
Thread.sleep(1000);
System.out.println("Time left before next run " + f.getDelay(TimeUnit.MILLISECONDS));
prints
run
Time left before next run 8999
Using scheduledFuture.get() you can get a handle to the task, and in case this task needs to be cancelled say manually from the UserInterface or based on some conditions like the null, the handle can be used to cancel it.
来源:https://stackoverflow.com/questions/25049021/what-is-the-purpose-of-scheduledfuture-get-method-if-is-retrieved-from-the-sch