Java Scheduler ScheduledExecutorService ScheduledThreadPoolExecutor Example(ScheduledThreadPoolExecutor例子——了解如何创建一个周期任务)
Welcome to the Java Scheduler Example. Today we will look into ScheduledExecutorService and it’s implementation class ScheduledThreadPoolExecutor example.
Table of Contents [hide]
Java Scheduler ScheduledExecutorService

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
Copy
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.
Copy
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<<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:
If you have come this far, it means that you liked what you are reading. Why not reach little more and connect with me directly on Google Plus, Facebook or Twitter. I would love to hear your thoughts and opinions on my articles directly. Recently I started creating video tutorials too, so do check out my videos on Youtube.
About Pankaj
Java Scheduler ScheduledExecutorService ScheduledThreadPoolExecutor Example(ScheduledThreadPoolExecutor例子——了解如何创建一个周期任务)的更多相关文章
- ThreadPoolExecutor – Java Thread Pool Example(如何使用Executor框架创建一个线程池)
Java thread pool manages the pool of worker threads, it contains a queue that keeps tasks waiting to ...
- Java开源报表Jasper入门(2) -- 使用JasperSoft Studio创建一个简单报表
在接下来的教程中,我们将实现一个简单的JasperReports示例,展现其基本的开发.使用流程.文章很长,不过是以图片居多,文字并不多. 实例中使用最新的Jasper Studio5.2进行报表设计 ...
- 借助 Java 9 Jigsaw,如何在 60 秒内创建 JavaFX HelloWorld 程序?
[编者按]本文作者为 Carl Dea,主要介绍利用 Jigsaw 项目在大约一分钟内编写标准化的"Hello World"消息代码.本文系国内 ITOM 管理平台 OneAPM ...
- java 多线程——quartz 定时调度的例子
java 多线程 目录: Java 多线程——基础知识 Java 多线程 —— synchronized关键字 java 多线程——一个定时调度的例子 java 多线程——quartz 定时调度的例子 ...
- [Java Web] 4、JavaScript 简单例子(高手略过)
内容概览: JavaScript简介 JavaScript的基本语法 JavaScript的基本应用 JavaScript的事件处理 window对象的使用 JavaScript简介: JavaScr ...
- java 23种设计模式及具体例子 收藏有时间慢慢看
设计模式(Design pattern)是一套被反复使用.多数人知晓的.经过分类编目的.代码设计经验的总结.使用设计模式是为了可重用代码.让代码更容易被他人理解.保证代 码可靠性. 毫无疑问,设计模式 ...
- rabbit的简单搭建,java使用rabbitmq queue的简单例子和一些坑
一 整合 由于本人的码云太多太乱了,于是决定一个一个的整合到一个springboot项目里面. 附上自己的项目地址https://github.com/247292980/spring-boot 以整 ...
- Java 守护线程(Daemon) 例子
当我们在Java中创建一个线程,缺省状态下它是一个User线程,如果该线程运行,JVM不会终结该程序.当一个线被标记为守护线程,JVM不会等待其结束,只要所有用户(User)线程都结束,JVM将终结程 ...
- java 三次样条插值 画光滑曲线 例子
java 三次样条插值 画光滑曲线 例子 主要是做数值拟合,根据sin函数采点,取得数据后在java中插值并在swing中画出曲线,下面为截图 不光滑和光滑曲线前后对比: 代码: 执行类: p ...
随机推荐
- 【Android】各式各样的弹出框与对菜单键、返回键的监听
Android自带各式各样的弹出框.弹出框也是安卓主要的组件之中的一个.同一时候安卓程序能够对菜单键.返回键的监听.但在安卓4.0之后就禁止对Home键的屏蔽与监听,强制保留为系统守护按键.假设非要对 ...
- MyReport.Form表单引擎
MyReport.Form表单引擎.主要提供表单模板的设计以及表单模板的预览填报等功能集合. 支持文本框.选择框.数字框.日期框.图片框.组合框.弹出框等经常使用控件. watermark/2/tex ...
- 使用cecil 完毕 code injection
1. 安装Mono.Cecil watermark/2/text/aHR0cDovL2Jsb2cuY3Nkbi5uZXQvbGFuX2xpYW5n/font/5a6L5L2T/fontsize/400 ...
- 浅析.Net数据操作机制
举个栗子,获取新闻详情的案例. public ActionResult NewsView(int newsId) { var news = _newsService.GetNewsById(newsI ...
- select选择框实现跳转
select选择框实现跳转 零.启示 1.启示把bom里面的几个对象稍微有点印象,那么主干有了,学其它的就感觉添置加瓦,很简单 就是关注树木的主干 2.万能的百度,不过当然要你基础好学得多才能看得懂, ...
- php中str_repeat函数
php中str_repeat函数 一.作用 用于repeat str 二.实例:输出菱形 代码: <!DOCTYPE html> <html lang="en"& ...
- Nginx安装以及配置
安装编译工具及库文件 1 yum -y install make zlib zlib-devel gcc-c++ libtool openssl openssl-devel 安装 PCRE 下载 PC ...
- Unity 3D 开发 —— 脚本编程
Unity 相关资源 Unity 官网 :http://www.unity3D.com Unity 论坛 : http://forum.unity3d.com/forum.php Unity 问答 : ...
- 玩转redux--从会用到庖丁解牛
目录 为何而写 redux是什么 redux的设计哲学 redux的工作流 redux的几个核心要素 store action reducer actionCreator combineReducer ...
- 交换工资 SQL