Table of Contents
There are multiple ways to schedule a task in java. We have already Java timer to schedule a task but the problem with timers task is that you can execute one task at a time.So if the current task takes longer subsequent job will be delayed.
In this scenario, you can use Java ScheduledThreadPoolExecutor.This class is a part of Executor framework and provides facility to schedule a task rather than executing it immediately.
There are three methods which you can use to schedule task using ScheduledThreadPoolExecutor.
Java ScheduledThreadPoolExecutor Example:
Step 1: Create a Runnable task named “RunnableTask.java”.
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 |
package org.arpit.java2blog; import java.util.Date; public class RunnableTask implements Runnable{ private String taskName; public RunnableTask(String s){ this.taskName=s; } @Override public void run() { System.out.println(Thread.currentThread().getName()+" Start Time for "+taskName+" "+new Date()); // Process task here try { Thread.sleep(5000); } catch (InterruptedException e) { e.printStackTrace(); } System.out.println(Thread.currentThread().getName()+" End Time for "+taskName+" "+new Date()); } @Override public String toString(){ return this.taskName; } } |
Step 2:
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 |
package org.arpit.java2blog; import java.util.Date; import java.util.concurrent.Executors; import java.util.concurrent.ScheduledExecutorService; import java.util.concurrent.TimeUnit; public class ScheduledThreadPoolMain { public static void main(String[] args) throws InterruptedException { System.out.println("Current Time = "+new Date()); // Created ScheduledThreadPoolExecutor object ScheduledExecutorService scheduledThreadPool = Executors.newScheduledThreadPool(3); for(int i=1; i<=3; i++){ Thread.sleep(2000); RunnableTask task = new RunnableTask("Task "+i); scheduledThreadPool.schedule(task,5, TimeUnit.SECONDS); } // Adding some delay Thread.sleep(10000); scheduledThreadPool.shutdown(); System.out.println("Completed all threads"); } } |
Let’s understand more about above main method.
1 2 3 |
ScheduledExecutorService scheduledThreadPool = Executors.newScheduledThreadPool(3); |
ScheduledThreadPoolExecutor also have factory method named newScheduledThreadPool in Executors class similar to newFixedThreadPoolExecutor and newCachedThreadPoolExectuor.
You need to call schedule method to schedule as a task.
Schedule method takes three arguments:
public ScheduledFuture<?> schedule(Runnable command,long delay, TimeUnit unit):
Runnable command: It represents the task which you want to schedule.
long delay: It represents inital delay after which you want to schedule the task.
TimeUnit unit: It is time measure for delay argument.
If you notice, schedule method returns object of ScheduledFuture<?> which you can use to get the status of submitted jobs.
We have also called scheduledThreadPool.shutdown(), shutdown() method will bydefault wait for submitted task to execute and then terminate. You can change this policy using setExecuteExistingDelayedTasksAfterShutdownPolicy().
When you run above program, you will get below output:
pool-1-thread-1 Start Time for Task 1 Fri May 19 00:20:46 IST 2017
pool-1-thread-2 Start Time for Task 2 Fri May 19 00:20:48 IST 2017
pool-1-thread-3 Start Time for Task 3 Fri May 19 00:20:50 IST 2017
pool-1-thread-1 End Time for Task 1 Fri May 19 00:20:51 IST 2017
pool-1-thread-2 End Time for Task 2 Fri May 19 00:20:53 IST 2017
pool-1-thread-3 End Time for Task 3 Fri May 19 00:20:55 IST 2017
Completed all threads
ScheduledThreadPoolExecutor’s scheduleAtFixedRate example:
ScheduledThreadPoolExecutor’s scheduleAtFixedRate is used to schedule a task after fix delay and then execute that task periodically.
scheduleAtFixedRate method takes four arguments:
public ScheduledFuture<?> scheduleAtFixedRate(Runnable command,long initialDelay,long period,TimeUnit unit)
Runnable command: It represents the task which you want to schedule.
long initialDelay: It represents initial delay after which you want to schedule the task.
long period: It represents period by which you want to repeat the task.
TimeUnit unit: It is time measure for delay argument.
Let’s do some changes to call scheduleAtFixedRate in ScheduledThreadPoolMain.
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 |
package org.arpit.java2blog; import java.util.Date; import java.util.concurrent.Executors; import java.util.concurrent.ScheduledExecutorService; import java.util.concurrent.TimeUnit; public class ScheduledThreadPoolMain { /** * @param args * @throws InterruptedException */ public static void main(String[] args) throws InterruptedException { System.out.println("Current Time = "+new Date()); // Created ScheduledThreadPoolExecutor object ScheduledExecutorService scheduledThreadPool = Executors.newScheduledThreadPool(3); for(int i=1; i<=3; i++){ Thread.sleep(2000); RunnableTask task = new RunnableTask("Task "+i); scheduledThreadPool.scheduleAtFixedRate(task,5,10,TimeUnit.SECONDS); } // Adding some delay Thread.sleep(15000); scheduledThreadPool.shutdown(); while(!scheduledThreadPool.isTerminated()){ //wait for all tasks to finish } System.out.println("Completed all threads"); } } |
When you run above program, you will get below output:
pool-1-thread-1 Start Time for Task 1 Fri May 19 00:56:36 IST 2017
pool-1-thread-2 Start Time for Task 2 Fri May 19 00:56:38 IST 2017
pool-1-thread-3 Start Time for Task 3 Fri May 19 00:56:40 IST 2017
pool-1-thread-1 End Time for Task 1 Fri May 19 00:56:41 IST 2017
pool-1-thread-2 End Time for Task 2 Fri May 19 00:56:43 IST 2017
pool-1-thread-3 End Time for Task 3 Fri May 19 00:56:45 IST 2017
pool-1-thread-1 Start Time for Task 1 Fri May 19 00:56:46 IST 2017
pool-1-thread-2 Start Time for Task 2 Fri May 19 00:56:48 IST 2017
pool-1-thread-3 Start Time for Task 3 Fri May 19 00:56:50 IST 2017
pool-1-thread-1 End Time for Task 1 Fri May 19 00:56:51 IST 2017
pool-1-thread-2 End Time for Task 2 Fri May 19 00:56:53 IST 2017
pool-1-thread-3 End Time for Task 3 Fri May 19 00:56:55 IST 2017
Completed all threads
If Observe the output carefully:
pool-1-thread-1 Start Time for Task 1 Fri May 19 00:56:46 IST 2017
Once task 1 started, next task scheduled after period of 10 secs which have provided in scheduleAtFixedRate method.
ScheduledThreadPoolExecutor’s scheduleWithFixedDelay example:
ScheduledThreadPoolExecutor’s scheduleWithFixedDelay is used to schedule a task after initial delay and then execute tasks with fixed delay after completion of the previous task.
Let’s do some changes to call scheduleWithFixedDelay in ScheduledThreadPoolMain.
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 |
package org.arpit.java2blog; import java.util.Date; import java.util.concurrent.Executors; import java.util.concurrent.ScheduledExecutorService; import java.util.concurrent.TimeUnit; public class ScheduledThreadPoolMain { /** * @param args * @throws InterruptedException */ public static void main(String[] args) throws InterruptedException { System.out.println("Current Time = "+new Date()); // Created ScheduledThreadPoolExecutor object ScheduledExecutorService scheduledThreadPool = Executors.newScheduledThreadPool(3); for(int i=1; i<=3; i++){ Thread.sleep(2000); RunnableTask task = new RunnableTask("Task "+i); scheduledThreadPool.scheduleWithFixedDelay(task,5,10,TimeUnit.SECONDS); } // Adding some delay Thread.sleep(30000); scheduledThreadPool.shutdown(); while(!scheduledThreadPool.isTerminated()){ //wait for all tasks to finish } System.out.println("Completed all threads"); } } |
Current Time = Fri May 19 00:50:53 IST 2017
pool-1-thread-1 Start Time for Task 1 Fri May 19 00:51:00 IST 2017
pool-1-thread-2 Start Time for Task 2 Fri May 19 00:51:02 IST 2017
pool-1-thread-3 Start Time for Task 3 Fri May 19 00:51:04 IST 2017
pool-1-thread-1 End Time for Task 1 Fri May 19 00:51:05 IST 2017
pool-1-thread-2 End Time for Task 2 Fri May 19 00:51:07 IST 2017
pool-1-thread-3 End Time for Task 3 Fri May 19 00:51:09 IST 2017
pool-1-thread-1 Start Time for Task 1 Fri May 19 00:51:15 IST 2017
pool-1-thread-2 Start Time for Task 2 Fri May 19 00:51:17 IST 2017
pool-1-thread-3 Start Time for Task 3 Fri May 19 00:51:19 IST 2017
pool-1-thread-1 End Time for Task 1 Fri May 19 00:51:20 IST 2017
pool-1-thread-2 End Time for Task 2 Fri May 19 00:51:22 IST 2017
pool-1-thread-3 End Time for Task 3 Fri May 19 00:51:24 IST 2017
Completed all threads
If Observe the output carefully:
pool-1-thread-1 Start Time for Task 1 Fri May 19 00:51:15 IST 2017
Once task 1 ended, next task scheduled after delay of 10 secs which have provided in scheduleWithFixedDelay method.
that’s all about Java ScheduledThreadPoolExecutor Example.