LeetCode - The World's Leading Online Programming Learning Platform

Question

Implement following method of ScheduledExecutorService interface in Java

schedule(Runnable command, long delay, TimeUnit unit)

Creates and executes a one-shot action that becomes enabled after the given delay.

scheduleAtFixedRate(Runnable command, long initialDelay, long period, TimeUnit unit)

Creates and executes a periodic action that becomes enabled first after the given initial delay, and subsequently with the given period; that is executions will commence after initialDelay then initialDelay+period, then initialDelay + 2 * period, and so on.

scheduleWithFixedDelay(Runnable command, long initialDelay, long delay, TimeUnit unit)

Creates and executes a periodic action that becomes enabled first after the given initial delay, and subsequently with the given delay between the termination of one execution and the commencement of the next.

Solution:

import java.util.concurrent.*;
import java.util.concurrent.atomic.AtomicBoolean;

public class SimpleScheduler {

private final ScheduledExecutorService executor = Executors.newScheduledThreadPool(1);

public void schedule(Runnable command, long delay, TimeUnit unit) { executor.schedule(command, delay, unit); }

public void scheduleAtFixedRate(Runnable command, long initialDelay, long period, TimeUnit unit) { executor.scheduleAtFixedRate(command, initialDelay, period, unit); }

public void scheduleWithFixedDelay(Runnable command, long initialDelay, long delay, TimeUnit unit) { executor.scheduleWithFixedDelay(command, initialDelay, delay, unit); }

public void shutdown() { executor.shutdown(); }

public static void main(String[] args) { SimpleScheduler scheduler = new SimpleScheduler();

Runnable task = () -> System.out.println("Running at: " + System.currentTimeMillis());

System.out.println("Scheduling one-shot task...");
scheduler.schedule(task, 2, TimeUnit.SECONDS);

System.out.println("Scheduling fixed-rate task...");
scheduler.scheduleAtFixedRate(task, 1, 3, TimeUnit.SECONDS);

System.out.println("Scheduling fixed-delay task...");
scheduler.scheduleWithFixedDelay(task, 1, 4, TimeUnit.SECONDS);

}


}

Question: