Java Scheduler ScheduledExecutorService ScheduledThreadPoolExecutor Example(ScheduledThreadPoolEx...

Wesley13
• 阅读 979

Welcome to the Java Scheduler Example. Today we will look into ScheduledExecutorService and it’s implementation class ScheduledThreadPoolExecutor example.

Java Scheduler ScheduledExecutorService

Java Scheduler ScheduledExecutorService ScheduledThreadPoolExecutor Example(ScheduledThreadPoolEx...
Sometimes we need to execute a task periodically or after specific delay. Java provides Timer Class through which we can achieve this but sometimes we need to run similar tasks in parallel. So creating multiple Timer objects will be an overhead to the system and it’s better to have a thread pool of scheduled tasks.

Java provides scheduled thread pool implementation through ScheduledThreadPoolExecutor class that implements ScheduledExecutorService interface. ScheduledExecutorService defines the contract methods to schedule a task with different options.

Sometime back I wrote a post about Java ThreadPoolExecutor where I was using Executors class to create the thread pool. Executors class also provide factory methods to create ScheduledThreadPoolExecutor where we can specify the number of threads in the pool.

Java Scheduler Example

Let’s say we have a simple Runnable class like below.

WorkerThread.java

 package 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; } } 

It’s a simple Runnable class that takes around 5 seconds to execute its task.

Let’s see a simple example where we will schedule the worker thread to execute after 10 seconds delay. We will use Executors class newScheduledThreadPool(int corePoolSize) method that returns instance of ScheduledThreadPoolExecutor. Here is the code snippet from Executors class.

 public static ScheduledExecutorService newScheduledThreadPool(int corePoolSize) { return new ScheduledThreadPoolExecutor(corePoolSize); } 

Below is our java scheduler example program using ScheduledExecutorService and ScheduledThreadPoolExecutor implementation.

Copy
package 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 {

<span class="hljs-function"><span class="hljs-keyword">public</span> <span class="hljs-keyword">static</span> <span class="hljs-keyword">void</span> <span class="hljs-title">main</span><span class="hljs-params">(String[] args)</span> <span class="hljs-keyword">throws</span> InterruptedException </span>{
    ScheduledExecutorService scheduledThreadPool = Executors.newScheduledThreadPool(<span class="hljs-number">5</span>);
    
    
    <span class="hljs-comment">//schedule to run after sometime</span>
    System.out.println(<span class="hljs-string">"Current Time = "</span>+<span class="hljs-keyword">new</span> Date());
    <span class="hljs-keyword">for</span>(<span class="hljs-keyword">int</span> i=<span class="hljs-number">0</span>; i&lt;<span class="hljs-number">3</span>; i++){
        Thread.sleep(<span class="hljs-number">1000</span>);
        WorkerThread worker = <span class="hljs-keyword">new</span> WorkerThread(<span class="hljs-string">"do heavy processing"</span>);
        scheduledThreadPool.schedule(worker, <span class="hljs-number">10</span>, TimeUnit.SECONDS);
    }
    
    <span class="hljs-comment">//add some delay to let some threads spawn by scheduler</span>
    Thread.sleep(<span class="hljs-number">30000</span>);
    
    scheduledThreadPool.shutdown();
    <span class="hljs-keyword">while</span>(!scheduledThreadPool.isTerminated()){
        <span class="hljs-comment">//wait for all tasks to finish</span>
    }
    System.out.println(<span class="hljs-string">"Finished all threads"</span>);
}

}

When we run above java scheduler example program, we get following output that confirms that tasks are running with 10 seconds delay.

Copy
Current Time = Tue Oct 29 15:10:03 IST 2013 pool-1-thread-1 Start. Time = Tue Oct 29 15:10:14 IST 2013 pool-1-thread-2 Start. Time = Tue Oct 29 15:10:15 IST 2013 pool-1-thread-3 Start. Time = Tue Oct 29 15:10:16 IST 2013 pool-1-thread-1 End. Time = Tue Oct 29 15:10:19 IST 2013 pool-1-thread-2 End. Time = Tue Oct 29 15:10:20 IST 2013 pool-1-thread-3 End. Time = Tue Oct 29 15:10:21 IST 2013 Finished all threads

Note that all the schedule() methods return instance of ScheduledFuture that we can use to get the thread state information and delay time for the thread.

ScheduledFuture extends Future interface, read more about them at Java Callable Future Example.

There are two more methods in ScheduledExecutorService that provide option to schedule a task to run periodically.

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

We can use ScheduledExecutorService scheduleAtFixedRate method to schedule a task to run after initial delay and then with the given period.

The time period is from the start of the first thread in the pool, so if you are specifying period as 1 second and your thread runs for 5 second, then the next thread will start executing as soon as the first worker thread finishes it’s execution.

For example, if we have code like this:

Copy
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); }

Then we will get output like below.

Copy
Current Time = Tue Oct 29 16:10:00 IST 2013 pool-1-thread-1 Start. Time = Tue Oct 29 16:10:01 IST 2013 pool-1-thread-2 Start. Time = Tue Oct 29 16:10:02 IST 2013 pool-1-thread-3 Start. Time = Tue Oct 29 16:10:03 IST 2013 pool-1-thread-1 End. Time = Tue Oct 29 16:10:06 IST 2013 pool-1-thread-2 End. Time = Tue Oct 29 16:10:07 IST 2013 pool-1-thread-3 End. Time = Tue Oct 29 16:10:08 IST 2013 pool-1-thread-1 Start. Time = Tue Oct 29 16:10:11 IST 2013 pool-1-thread-4 Start. Time = Tue Oct 29 16:10:12 IST 2013

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

ScheduledExecutorService scheduleWithFixedDelay method can be used to start the periodic execution with initial delay and then execute with given delay. The delay time is from the time thread finishes it’s execution. So if we have code like below:

Copy
for (int i = 0; i < 3; i++) { Thread.sleep(1000); WorkerThread worker = new WorkerThread("do heavy processing"); scheduledThreadPool.scheduleWithFixedDelay(worker, 0, 1, TimeUnit.SECONDS); }

Then we will get output like below.

Copy
Current Time = Tue Oct 29 16:14:13 IST 2013 pool-1-thread-1 Start. Time = Tue Oct 29 16:14:14 IST 2013 pool-1-thread-2 Start. Time = Tue Oct 29 16:14:15 IST 2013 pool-1-thread-3 Start. Time = Tue Oct 29 16:14:16 IST 2013 pool-1-thread-1 End. Time = Tue Oct 29 16:14:19 IST 2013 pool-1-thread-2 End. Time = Tue Oct 29 16:14:20 IST 2013 pool-1-thread-1 Start. Time = Tue Oct 29 16:14:20 IST 2013 pool-1-thread-3 End. Time = Tue Oct 29 16:14:21 IST 2013 pool-1-thread-4 Start. Time = Tue Oct 29 16:14:21 IST 2013

That’s all for java scheduler example. We learned about ScheduledExecutorService and ScheduledThreadPoolExecutorthread too. You should check other articles about Multithreading in Java.

References:

点赞
收藏
评论区
推荐文章
blmius blmius
3年前
MySQL:[Err] 1292 - Incorrect datetime value: ‘0000-00-00 00:00:00‘ for column ‘CREATE_TIME‘ at row 1
文章目录问题用navicat导入数据时,报错:原因这是因为当前的MySQL不支持datetime为0的情况。解决修改sql\mode:sql\mode:SQLMode定义了MySQL应支持的SQL语法、数据校验等,这样可以更容易地在不同的环境中使用MySQL。全局s
待兔 待兔
5个月前
手写Java HashMap源码
HashMap的使用教程HashMap的使用教程HashMap的使用教程HashMap的使用教程HashMap的使用教程22
Wesley13 Wesley13
3年前
java反射, 不看你可别后悔
<divid"content\_views"class"markdown\_views"<!flowchart箭头图标勿删<svgxmlns"http://www.w3.org/2000/svg"style"display:none;"<pathstrokelinecap"round"d"M5,00,
Stella981 Stella981
3年前
AndroidStudio封装SDK的那些事
<divclass"markdown\_views"<!flowchart箭头图标勿删<svgxmlns"http://www.w3.org/2000/svg"style"display:none;"<pathstrokelinecap"round"d"M5,00,2.55,5z"id"raphael
Stella981 Stella981
3年前
LocalDateTime计算时间差
<divclass"htmledit\_views"id"content\_views"<pLocalDateTime为java8的新特性之一<br</p<p<br</p<pLocalDateTime.now()获得当前时间<br</p<p</p<h5</h5<divstyle"marginleft
Stella981 Stella981
3年前
ASMSupport教程4.2
<h24.2生成Return操作</h2<p这一节我们将讲述如何生成return操作,我们将生成如下代码:</p<divstyle"paddingbottom:0px;margin:0px;paddingleft:0px;paddingright:0px;display:inline;float:none;pa
Wesley13 Wesley13
3年前
Java8中的LocalDateTime工具类
<divid"content\_views"class"markdown\_views"<!flowchart箭头图标勿删<svgxmlns"http://www.w3.org/2000/svg"style"display:none;"<pathstrokelinecap"round"d"M5,00,
Wesley13 Wesley13
3年前
00:Java简单了解
浅谈Java之概述Java是SUN(StanfordUniversityNetwork),斯坦福大学网络公司)1995年推出的一门高级编程语言。Java是一种面向Internet的编程语言。随着Java技术在web方面的不断成熟,已经成为Web应用程序的首选开发语言。Java是简单易学,完全面向对象,安全可靠,与平台无关的编程语言。
Stella981 Stella981
3年前
Docker 部署SpringBoot项目不香吗?
  公众号改版后文章乱序推荐,希望你可以点击上方“Java进阶架构师”,点击右上角,将我们设为★“星标”!这样才不会错过每日进阶架构文章呀。  !(http://dingyue.ws.126.net/2020/0920/b00fbfc7j00qgy5xy002kd200qo00hsg00it00cj.jpg)  2
Stella981 Stella981
3年前
React Native 开发豆瓣评分(八)首页开发
首页完成效果展示:<divstyle"textalign:center;"<imgsrc"https://img2018.cnblogs.com/blog/1312841/201907/1312841201907181353098021875493361.gif"/</div一、开发占位图组件在没有数