What is the purpose of the ScheduledFuture.get () method if it is retrieved from the scheduleWithFixedDelay / scheduleAtFixedRate method

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 can get the value later via scheduledFuture.get(5, TimeUnit.SECONDS) or scheduledFuture.get() and must be null because the task completed only once and it completed. And null , because I'm working with a version of the shedule Runnable method, not a version of the shedule Callable method. It conforms to the API

So far, I'm fine.

My question is:

What is the purpose of ScheduledFuture if it is retrieved from the scheduleWithFixedDelay method (even from scheduleAtFixedRate ):

 ScheduledFuture<?> scheduledFuture= scheduledThreadPoolExecutor.scheduleWithFixedDelay(myClassRunnable, 1, 5, TimeUnit.SECONDS); 

Yes, I know that both fixed methods perform the same task many times until the ScheduledThreadPoolExecutor shutdown method is called (it should stop all scheduled tasks).

I did a Google search to find some examples, using the ScheduledFuture returned from scheduleWithFixedDelay , I only found the undo method to undo a specific task. But no one works with get .

I don’t know if I am mistaken, but the get method seems useless if we work with scheduleWithFixedDelay , because if I use later:

  • scheduleFuture.get () - it remains on hold, and the Runnable object continues to work many times (start, end, delay, start, etc.)
  • scheduleFuture.get (32, TimeUnit.SECONDS) - TimeoutException is always displayed

I thought I would be able to get a null value, since I can use the period argument / parameter from the scheduleWithFixedDelay method. I mean : run the Runnable object, wait for it to complete, and use the scheduleFuture.get () function to get a null value confirming that it was completed. Expect a delay time period to restart the Runnable object according to the value of period , etc.

Clarifications and examples are fully welcome.

Thanks in advance.

+8
java java.util.concurrent
source share
1 answer

ScheduledFuture can be used to get the time to complete the following task:

  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 
+3
source share

All Articles