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 ...
随机推荐
- 常用Linux命令 mount df dd
mount -t tmpfs tmpfs ~/build -o size=1G -t 对应的是类型 -o 对应的是选项 tmpfs是Linux/Unix系统上的一种基于内存的文件系统.tmpfs可以使 ...
- 实战c++中的string系列--string的替换、查找(一些与路径相关的操作)
今天继续写一些string操作. string给我们提供了非常多的方法,可是每在使用的时候,就要费些周折. 场景1: 得到一个std::string full_path = "D:\prog ...
- crontab FAQ
1.crontab变量问题 crontab中的脚本须要引入系统变量才干找到,否则crontab中的命令找不到系统变量,或者都写绝对路径. 2.1分钟运行一次 */1 * * * * /etc/keep ...
- Redis学习手冊(事务)
一.概述: 和众多其他数据库一样,Redis作为NoSQL数据库也相同提供了事务机制. 在Redis中,MULTI/EXEC/DISCARD/WATCH这四个命令是我们实现事务的基石. 相 ...
- HDU 4173 Party Location(计算几何,枚举)
HDU 4173 题意:已知n(n<=200)位參赛选手的住所坐标.现要邀请尽可能多的选手来參加一个party,而每一个选手对于离住所超过2.5Km的party一律不去,求最多能够有多少个选手去 ...
- 使用无线局域网(WLAN)更需要注意加强安全防范
下面链接介绍对WLAN的安全加密部分的内容,主要对WinAircrackPack工具的在Wlan方面的应用分析,介绍常见几种的加密方式,以及再使用无线设备时候的注意事项.650) thi ...
- 【技能】Ext.Viewport 实现左三右一排列方式。
1.Extjs 布局非常是灵活.可是吐槽下CSS,太难重写,想自己重构一套都难哎... var viewport = new Ext.Viewport({ layout:'border', items ...
- c++操作当前窗体句柄
句柄 这一概念是MFC里的一个类.MFC有专门的函数来获取窗体句柄. HWND hwnd; hwnd=CreateWindow("my own windowshandle",&qu ...
- 【基础练习】【线性DP】codevs2622 数字序列(最大连续子序列和)题解
版权信息 转载请注明出处 [ametake版权全部]http://blog.csdn.net/ametake欢迎来看 这道题目本质就是朴素的最大连续子序列和 直接上题目和代码 题目描写叙述 Descr ...
- [NowCoder]牛客OI周赛1 题解
A.分组 首先,认识的人不超过3个,因此不存在无解的方案 考虑直接构造,先把所有点设为1,顺序扫一遍把有问题的点加入队列 每次取队头,将其颜色取反,再更新有问题的点 复杂度:考虑到每个点不会操作2次, ...