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

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&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:


About Pankaj

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.

Java Scheduler ScheduledExecutorService ScheduledThreadPoolExecutor Example(ScheduledThreadPoolExecutor例子——了解如何创建一个周期任务)的更多相关文章

  1. ThreadPoolExecutor – Java Thread Pool Example(如何使用Executor框架创建一个线程池)

    Java thread pool manages the pool of worker threads, it contains a queue that keeps tasks waiting to ...

  2. Java开源报表Jasper入门(2) -- 使用JasperSoft Studio创建一个简单报表

    在接下来的教程中,我们将实现一个简单的JasperReports示例,展现其基本的开发.使用流程.文章很长,不过是以图片居多,文字并不多. 实例中使用最新的Jasper Studio5.2进行报表设计 ...

  3. 借助 Java 9 Jigsaw,如何在 60 秒内创建 JavaFX HelloWorld 程序?

    [编者按]本文作者为 Carl Dea,主要介绍利用 Jigsaw 项目在大约一分钟内编写标准化的"Hello World"消息代码.本文系国内 ITOM 管理平台 OneAPM ...

  4. java 多线程——quartz 定时调度的例子

    java 多线程 目录: Java 多线程——基础知识 Java 多线程 —— synchronized关键字 java 多线程——一个定时调度的例子 java 多线程——quartz 定时调度的例子 ...

  5. [Java Web] 4、JavaScript 简单例子(高手略过)

    内容概览: JavaScript简介 JavaScript的基本语法 JavaScript的基本应用 JavaScript的事件处理 window对象的使用 JavaScript简介: JavaScr ...

  6. java 23种设计模式及具体例子 收藏有时间慢慢看

    设计模式(Design pattern)是一套被反复使用.多数人知晓的.经过分类编目的.代码设计经验的总结.使用设计模式是为了可重用代码.让代码更容易被他人理解.保证代 码可靠性. 毫无疑问,设计模式 ...

  7. rabbit的简单搭建,java使用rabbitmq queue的简单例子和一些坑

    一 整合 由于本人的码云太多太乱了,于是决定一个一个的整合到一个springboot项目里面. 附上自己的项目地址https://github.com/247292980/spring-boot 以整 ...

  8. Java 守护线程(Daemon) 例子

    当我们在Java中创建一个线程,缺省状态下它是一个User线程,如果该线程运行,JVM不会终结该程序.当一个线被标记为守护线程,JVM不会等待其结束,只要所有用户(User)线程都结束,JVM将终结程 ...

  9. java 三次样条插值 画光滑曲线 例子

    java 三次样条插值 画光滑曲线 例子 主要是做数值拟合,根据sin函数采点,取得数据后在java中插值并在swing中画出曲线,下面为截图  不光滑和光滑曲线前后对比:    代码: 执行类: p ...

随机推荐

  1. 父类与子类的virtual

    父类加了virtual,子类不需要加virtual,多余.加了也不会报错. 父类中不是virtual,子类是virtual,那么父类中的不是虚函数,子类及子子类的派生类中该函数才是虚函数

  2. Peer To Peer——对等网络

    今年的考试.大问题没怎么出现. 就是考英语第二天的下午,发生网络阻塞的现象,不影响大局.可是事出有因,我们还是须要看看是什么影响到了考生抽题.最后查了一圈,发现其它几场的英语考试听力都是19M大小,而 ...

  3. codeforce 571 B Minimization

    题意:给出一个序列,经过合适的排序后.使得最小. 做法:将a升序排序后,dp[i][j]:选择i个数量为n/k的集合,选择j个数量为n/k+1的集合的最小值. 举个样例, a={1,2,3,4,5,6 ...

  4. [易飞]一张领料单单身仓库&quot;飞了&quot;引起的思考

    [摘要]我司每月月初10号前財务要出报表.故10号前要做完毕本月结. PMC经理接到仓管员反馈. 物料-30408011003在账上怎么还有那么多?上次发料的时候已发完. 相应的领料单:5403-20 ...

  5. layer:web弹出层解决方案

    layer:web弹出层解决方案 一.总结 一句话总结:http://layer.layui.com/ 1.layer中弹出层tips的使用(代码)是怎样的? 使用还是比较简单方便的 //tips层- ...

  6. CSS动态实现文本框清除按钮的隐藏与显示

    当前现代浏览器中,Chrome浏览器下type=search的输入框会有清除按钮的动态呈现,不过搜索input框尺寸不太好控制(padding无视):FireFox浏览器貌似任何类型的输入框都无动于衷 ...

  7. Elasticsearch之源码编译

    前期博客 Elasticsearch之下载源码 步骤 (1)首先去git下载源码 https://github.com/elastic/elasticsearch/tree/v2.4.3 下载下来,得 ...

  8. vuejs实现表格分页

    http://www.cnblogs.com/landeanfen/p/6054654.html#_label3_8 <html xmlns="http://www.w3.org/19 ...

  9. Kinect 开发 —— 开发前的准备工作

    Kinect SDK v1.5 支持托管语言和非托管语言 Xbox360的游戏是基于Xbox360开发工具包 (XDK)开发的,Xbox 360和Windows是两个完全不同的系统架构.使用Kinec ...

  10. day 5 集合

    # -*- coding: utf_8 _*_# Author:Vi#集合是无序的 list_1 = [1,2,3,2,3,5,7]list_1 = set(list_1)#将列表转变成集合list_ ...