package com.ab.concurrent.samples;

import java.util.concurrent.*;
import java.util.logging.Logger;

/**
 * Created by Abey on 1/12/2017.
 */
public class ScheduledExecutorSample {

    private static Logger log = Logger.getLogger(ScheduledExecutorSample.class.getName());
    public static void main(String... args)
    {
        ScheduledExecutorService executor = Executors.newScheduledThreadPool(1);
        ScheduledExecutorService executor2 = Executors.newScheduledThreadPool(1);
        ScheduledExecutorService executor3 = Executors.newScheduledThreadPool(1);

        Runnable task = () -> log.info("Scheduling: " + System.nanoTime());

        try {
            ScheduledFuture<?> future = executor.schedule(createTask("Task One"), 3, TimeUnit.SECONDS);
            ScheduledFuture<?> future2 = executor2.scheduleAtFixedRate(createTask("Task Multi fixed rate "), 1, 1, TimeUnit.SECONDS);
            ScheduledFuture<?> future3 = executor3.scheduleWithFixedDelay(createTask("Task Multi with delay"), 1, 1, TimeUnit.SECONDS);
            TimeUnit.MILLISECONDS.sleep(1337);
            long remainingDelay = future.getDelay(TimeUnit.MILLISECONDS);
            log.info("Remaining Delay: " + remainingDelay);
            TimeUnit.MINUTES.sleep(2);
        } catch (InterruptedException e) {
            log.severe("InterruptedException " + e);
            e.printStackTrace();
        }

        shutdown(executor);
        shutdown(executor2);
        shutdown(executor3);
    }

    private static Runnable createTask(String msg)
    {
        return ()-> log.info(msg);
    }
    private static void shutdown(ExecutorService executor)
    {
        //shutdown
        try {
            Thread.sleep(TimeUnit.SECONDS.toSeconds(20));
            log.info("Shutting down executor...");
            executor.shutdown();
            executor.awaitTermination(5, TimeUnit.SECONDS);
        } catch (InterruptedException e) {
            log.info("executor interrupted");
        } finally {
            if (!executor.isTerminated())
                log.info("cancel non-finished tasks");
            executor.shutdownNow();
        }

    }
}
