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. SQL Server 为代码减负之存储过程

        存储过程能够用来提高数据库的查询效率.由于它事先被编译过.被储存于内存中,每次执行前.不必被从新编译,所以效率非常高. 存储过程是一组sql增删改查的集合,假设程序中的一个功能涉及到对数据库的 ...

  2. Spark MLlib Deep Learning Convolution Neural Network (深度学习-卷积神经网络)3.3

    3.Spark MLlib Deep Learning Convolution Neural Network(深度学习-卷积神经网络)3.3 http://blog.csdn.net/sunbow0 ...

  3. Http post提交和get提交

    public string  PostParameter(string url)         {  string message="";             GetOrde ...

  4. 2017国家集训队作业[agc004f]Namori

    2017国家集训队作业[agc004f]Namori 题意: 给你一颗树或环套树,树上有\(N\)个点,有\(M\)条边.一开始,树上的点都是白色,一次操作可以选择一条端点颜色相同的边,使它的端点颜色 ...

  5. 前端js中this指向及改变this指向的方法

    js中this指向是一个难点,花了很长时间来整理和学习相关的知识点. 一. this this是JS中的关键字, 它始终指向了一个对象, this是一个指针; 参考博文: JavaScript函数中的 ...

  6. Python修改文件内容

    工作中要写个脚本来修改文件的内容,然后就写了一个刷子: #coding:utf8 import os def modify_file(old_file, new_version, old_versio ...

  7. c# 多态的美丽(虚方法、抽象、接口实现)

    面向对象3大特性:封装.继承.多态. 面向对象2大原则: 1)里氏替换原则:子类可以给父类,父类不能赋给子类. 2)开放封闭原则: 封装变化,降低耦合.(对扩展开放,对修改封闭) ********** ...

  8. 【2017 Multi-University Training Contest - Team 2】 Regular polygon

    [Link]: [Description] 给你n个点整数点; 问你这n个点,能够组成多少个正多边形 [Solution] 整点只能构成正四边形. 则先把所有的边预处理出来; 枚举每某两条边为对角线的 ...

  9. ArcSDE:C#创建SDE要素数据集

    转自原文 ArcSDE:C#创建SDE要素数据集 /// <summary> /// 判断指定数据集是否存在 /// </summary> /// <param name ...

  10. java初始化过程中成员变量

    package day01; class Base{ int j; //1.j=0 Base(){ add(1); //2.调用子类add()方法 System.out.println(j); //4 ...