How to do it...

Follow these steps to implement the example:

  1. Create a class named Task and specify that it implements the Runnable interface:
        public class Task implements Runnable {
  1. Declare a private String attribute called name that will store the name of the task:
        private final String name;
  1. Implement the constructor of the class that initializes the attribute:
        public Task(String name) { 
this.name=name;
}
  1. Implement the run() method. Write a message to the console with the actual date to verify that the task is executed within the specified period:
        @Override 
public void run() {
System.out.printf("%s: Executed at: %s ",name,new Date());
}
  1. Implement the main class of the example by creating a class named Main and adding the main() method to it:
        public class Main { 
public static void main(String[] args) {
  1. Create ScheduledExecutorService using the newScheduledThreadPool() method of the Executors class. Pass 1 to this method as a parameter:
        ScheduledExecutorService executor=Executors
.newScheduledThreadPool(1);
  1. Write a message to the console with the actual date:
        System.out.printf("Main: Starting at: %s
",new Date());
  1. Create a new Task object:
        Task task=new Task("Task");
  1. Send this object to the executor using the scheduledAtFixRate() method. Use the tasks created earlier as parameters: the number one, the number two, and the constant TimeUnit.SECONDS. This method returns a ScheduledFuture object that you can use to control the status of the task:
        ScheduledFuture<?> result=executor.scheduleAtFixedRate(task, 1,
2, TimeUnit.SECONDS);
  1. Create a loop with 10 steps to write the time remaining for the next execution of the task. In the loop, use the getDelay() method of the ScheduledFuture object to get the number of milliseconds until the next execution of the task:
        for (int i=0; i<10; i++){ 
System.out.printf("Main: Delay: %d ",result
.getDelay(TimeUnit.MILLISECONDS));
  1. Sleep the thread during 500 milliseconds.
          try { 
TimeUnit.MILLISECONDS.sleep(500);
} catch (InterruptedException e) {
e.printStackTrace();
}
}
  1. Finish the executor using the shutdown() method:
        executor.shutdown();
  1. Put the thread to sleep for 5 seconds to verify that the periodic tasks have finished:
        try { 
TimeUnit.SECONDS.sleep(5);
} catch (InterruptedException e) {
e.printStackTrace();
}
  1. Write a message to indicate the end of the program:
        System.out.printf("Main: Finished at: %s
",new Date());
..................Content has been hidden....................

You can't read the all page of ebook, please click here login for view all page.
Reset
18.221.126.56