Close

Java - RunnableScheduledFuture Interface

[Last Updated: Oct 4, 2018]

RunnableScheduledFuture interface extends RunnableFuture<V> and ScheduledFuture<V>.

package java.util.concurrent;
 ....
public interface RunnableScheduledFuture<V> extends RunnableFuture<V>, ScheduledFuture<V> {
    boolean isPeriodic();
}

All methods in ScheduledExecutorService return an instance which implements RunnableScheduleFuture, that means we can cast the declared return type of ScheduledFuture to RunnableScheduledFuture.

Examples

package com.logicbig.example;

import java.util.concurrent.*;

public class RunnableScheduledFutureExample {
    public static void main(String[] args) throws ExecutionException, InterruptedException {
        Callable<Long> callable = new Callable<Long>() {
            @Override
            public Long call() throws Exception {
                return ThreadLocalRandom.current().nextLong();
            }
        };

        ScheduledExecutorService es = Executors.newSingleThreadScheduledExecutor();
        RunnableScheduledFuture<Long> scheduleFuture =
                (RunnableScheduledFuture<Long>) es.schedule(callable, 2, TimeUnit.SECONDS);
        System.out.println("remaining delay: " +scheduleFuture.getDelay(TimeUnit.MILLISECONDS));
        System.out.println("periodic: " +scheduleFuture.isPeriodic());
        Long result = scheduleFuture.get();
        System.out.println(result);
        es.shutdown();
    }
}
remaining delay: 1999
periodic: false
-5442858059467973343
package com.logicbig.example;

import java.util.concurrent.*;

public class RunnableScheduledFuturePeriodicExample {
    public static void main(String[] args) throws ExecutionException, InterruptedException {
        Runnable runnable = new Runnable() {
            @Override
            public void run() {
                System.out.println("running");
            }
        };

        ScheduledExecutorService es = Executors.newSingleThreadScheduledExecutor();
        RunnableScheduledFuture<?> scheduleFuture =
                (RunnableScheduledFuture<?>) es.scheduleAtFixedRate(runnable,
                        2, 1, TimeUnit.SECONDS);
        System.out.println("remaining delay: " + scheduleFuture.getDelay(TimeUnit.MILLISECONDS));
        System.out.println("periodic: " + scheduleFuture.isPeriodic());
        TimeUnit.SECONDS.sleep(5);
        scheduleFuture.cancel(true);
        es.shutdown();
    }
}
remaining delay: 1999
periodic: true
running
running
running
running

Example Project

Dependencies and Technologies Used:

  • JDK 11
  • Maven 3.5.4

RunnableScheduledFuture Example Select All Download
  • java-runnable-scheduled-future
    • src
      • main
        • java
          • com
            • logicbig
              • example
                • RunnableScheduledFutureExample.java

    See Also