- To execute a task periodically or after specific delay
- Option 1: Timer class
- Drawbacks: To run multiple similar tasks in parallel, we need multiple Timer objects
- Overhead to system
- No thread pool of scheduled tasks
- Drawbacks: To run multiple similar tasks in parallel, we need multiple Timer objects
- Option 2:
ScheduledThreadPoolExecutor- implementsScheduledExecutorServiceinterface- Defines contract methods to schedule task with different options
- Java ThreadPoolExecutor
- Executors also provide factory methods to construct
ScheduledThreadPoolExecutorto specify number of threads in pool
- Defines contract methods to schedule task with different options
-
WorkerThread.javapackage com.journaldev.threads; import java.util.Date; public class WorkerThread implements Runnable { private String command; public WorkerThread(String s) { this.command = s; } @Override public void run() { System.out.println(Thread.currentThread().getName() + "Start. Time = " + new Date()); processCommand(); System.out.println(Thread.currentThread().getName() + "End. Time = " + new Date()); } private void processCommand() { try { Thread.sleep(5000); } catch (InterruptedException e) { e.printStackTrace(); } } @override public String toString() { return this.command; } } -
Execute worker thread after 10 secods delay
-
newScheduledThreadPool(int corePoolSize)-
Returns instance of
ScheduledThreadPoolExecutorpublic static ScheduledExecutorService newScheduledThreadPool(int corePoolSize) { return new ScheduledThreadPoolExecutor(corePoolSize); }
-
-
Example: Using
ScheduledExecutorServiceandScheduledThreadPoolExecutorpackage com.journaldev.threads; import java.util.Date; import java.util.concurrent.Executors; import java.util.concurrent.ScheduledExecutorService; import java.util.concurrent.TimeUnit; public class ScheduledThreadPool { public static void main(String[] args) throws InterruptedException { ScheduledExecutorService scheduledThreadPool = Executors.newScheduledThreadPool(5); // schedule to run after sometime System.out.println("Current Time = " + new Date()); for (int i = 0; i < 3; i++) { Thread.sleep(1000); WorkerThread worker = new WorkerThread("do heavy processing"); scheduledThreadPool.schedule(worker, 10, TimeUnit.SECONDS); } // add some delay to let some threads spawn by scheduler Thread.sleep(30000); scheduledThreadPool.shutdown(); while(!scheduledThreadPool.isTermintated()) { // wait for all tasks to finish } System.out.println("Finished all threads"); } }schedule()- returns instance ofScheduledFuture- It can give thread state information
- It can give delay time for thread
- Extends
Futureinterface
-
-
Other methods exist to run tasks periodically
ScheduledExecutorService scheduleAtFixedRate(Runnable command, long initialDelay, long period, TimeUnit unit)
-
scheduleAtFixedRate- to schedule a task to run after initial delay and then with given period- Time period is from start of first thread in the pool
- If specified period is 1s, but threads runs for 5 seconds, next thread will start executing as soon as first worker thread finishes it's execution
- Time period is from start of first thread in the pool
-
Example:
for (int i = 0; i < 3; i++) { Thread.sleep(1000); WorkerThread worker = new WorkerThread("do heavy processing"); // schedule task to execute at fixed rate scheduledThreadPool.scheduleAtFixedRate(worker, 0, 10, TimeUnit.SECONDS); }
ScheduledExecutorService scheduleWithFixedDelay(Runnable command, long initialDelay, long delay, TimeUnit unit)
scheduleWithFixedDelaycan be used to start periodic execution with initial delay and then execute with given delay-
Delay time is from time thread finishes it's execution
for (int i = 0; i < 3; i++) { Thread.sleep(1000); WorkerThread worker = new WorkerThread("do heavy processing"); scheduledThreadPool.scheduleWithFixedDelay(worker, 0, 1, TimeUnit.SECONDS); }
-