Saturday 20 September 2014

ScheduledExecutorService

ScheduledExecutorService interface extends ExecutorService interface. By using ScheduledExecutorService you can schedule tasks to run after a given delay, or to execute periodically. The schedule methods create tasks with various delays and return a task object that can be used to cancel or check execution.

Below are the methods provided by ScheduledExecutorService interface.

Method Description
schedule(Callable<V> callable, long delay, TimeUnit unit) Creates and executes a ScheduledFuture that becomes enabled after the given delay.
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.
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 period.

public class Task implements Runnable{
    
   int taskNum;
   
   Task(int taskNum){
       this.taskNum = taskNum;
   }
    
   @Override
   public void run(){
       System.out.println(Thread.currentThread().getName() +" Started ");
       System.out.println(Thread.currentThread().getName() +" Finished ");
   }
}

import java.util.concurrent.*;

public class ScheduledExecutorServiceEx {
    public static void main(String args[]){
        ScheduledExecutorService scheduledExecutorService;
        
        scheduledExecutorService = Executors.newScheduledThreadPool(5);
        
        scheduledExecutorService.scheduleAtFixedRate(new Task(1), 2, 2, TimeUnit.SECONDS);
    }
}

Output
pool-1-thread-1 Started 
pool-1-thread-1 Finished 
pool-1-thread-1 Started 
pool-1-thread-1 Finished 
pool-1-thread-2 Started 
pool-1-thread-2 Finished 
pool-1-thread-1 Started 
pool-1-thread-1 Finished 
pool-1-thread-3 Started 
pool-1-thread-3 Finished 




Prevoius                                                 Next                                                 Home

No comments:

Post a Comment