Java java.util.Timer is a utility class that can be used to schedule a thread to be executed at certain time in future. Java Timer class can be used to schedule a task to be run one-time or to be run at regular intervals.

Java TimerTask

java.util.TimerTask is an abstract class that implements Runnable interface and we need to extend this class to create our own TimerTask that can be scheduled using java Timer class.

Java Timer Example

Java Timer class is thread safe and multiple threads can share a single Timer object without need for external synchronization. Timer class uses java.util.TaskQueue to add tasks at given regular interval and at any time there can be only one thread running the TimerTask, for example if you are creating a Timer to run every 10 seconds but single thread execution takes 20 seconds, then Timer object will keep adding tasks to the queue and as soon as one thread is finished, it will notify the queue and another thread will start executing.

Java Timer class uses Object wait and notify methods to schedule the tasks.

Here is a simple program for Java Timer and TimerTask example.


Copy
package com.journaldev.threads; import java.util.Date;
import java.util.Timer;
import java.util.TimerTask; public class MyTimerTask extends TimerTask { @Override
public void run() {
System.out.println("Timer task started at:"+new Date());
completeTask();
System.out.println("Timer task finished at:"+new Date());
} private void completeTask() {
try {
//assuming it takes 20 secs to complete the task
Thread.sleep(20000);
} catch (InterruptedException e) {
e.printStackTrace();
}
} public static void main(String args[]){
TimerTask timerTask = new MyTimerTask();
//running timer task as daemon thread
Timer timer = new Timer(true);
timer.scheduleAtFixedRate(timerTask, 0, 10*1000);
System.out.println("TimerTask started");
//cancel after sometime
try {
Thread.sleep(120000);
} catch (InterruptedException e) {
e.printStackTrace();
}
timer.cancel();
System.out.println("TimerTask cancelled");
try {
Thread.sleep(30000);
} catch (InterruptedException e) {
e.printStackTrace();
}
} }

Notice that one thread execution will take 20 seconds but Java Timer object is scheduled to run the task every 10 seconds. Here is the output of the program:


Copy
TimerTask started
Timer task started at:Wed Dec 26 19:16:39 PST 2012
Timer task finished at:Wed Dec 26 19:16:59 PST 2012
Timer task started at:Wed Dec 26 19:16:59 PST 2012
Timer task finished at:Wed Dec 26 19:17:19 PST 2012
Timer task started at:Wed Dec 26 19:17:19 PST 2012
Timer task finished at:Wed Dec 26 19:17:39 PST 2012
Timer task started at:Wed Dec 26 19:17:39 PST 2012
Timer task finished at:Wed Dec 26 19:17:59 PST 2012
Timer task started at:Wed Dec 26 19:17:59 PST 2012
Timer task finished at:Wed Dec 26 19:18:19 PST 2012
Timer task started at:Wed Dec 26 19:18:19 PST 2012
TimerTask cancelled
Timer task finished at:Wed Dec 26 19:18:39 PST 2012

The output confirms that if a task is already executing, Timer will wait for it to finish and once finished, it will start again the next task from the queue.

Java Timer object can be created to run the associated tasks as a daemon thread. Timer cancel() method is used to terminate the timer and discard any scheduled tasks, however it doesn’t interfere with the currently executing task and let it finish. If the timer is run as daemon thread, whether we cancel it or not, it will terminate as soon as all the user threads are finished executing.

Timer class contains several schedule() methods to schedule a task to run once at given date or after some delay. There are several scheduleAtFixedRate() methods to run a task periodically with certain interval.

While scheduling tasks using Timer, you should make sure that time interval is more than normal thread execution, otherwise tasks queue size will keep growing and eventually task will be executing always. That’s all for a quick roundup on Java Timer and Java TimerTask.



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 Timer TimerTask Example(java Timer的例子)的更多相关文章

  1. JAVA中的定时调度(Timer和TimerTask)

    某些时候我们需要定时去完成一些任务,这里举一个例子:我们需要在3秒钟后打印当前系统时间,此后每隔5秒重复此操作.代码如下: import java.util.TimerTask; import jav ...

  2. Java 工具类 —— 定时器(Timer/TimerTask)

    import java.util.Timer; import java.util.TimerTask; public class Timer { .... public void schedule(T ...

  3. 几种任务调度的 Java 实现方法与比较Timer,ScheduledExecutor,Quartz,JCronTab

    几种任务调度的 Java 实现方法与比较 综观目前的 Web 应用,多数应用都具备任务调度的功能.本文由浅入深介绍了几种任务调度的 Java 实现方法,包括 Timer,Scheduler, Quar ...

  4. JDK Timer & TimerTask

    目录 Timer & TimerTask Binary Heap Insert DELETE MIN PERFORMANCE LifeCycle Constructor MainLoop sc ...

  5. Java Timer, TimerTask, Timer.Schedule

    schedule的意思(时间表.进度表) timer.schedule(new TimerTask(){ void run()},0, 60*60*1000);timer.schedule(new M ...

  6. Java定时器Timer,TimerTask每隔一段时间随机生成数字

    1:java.util.Timer类是一种工具,线程用其安排以后在后台线程中执行的任务.可安排任务执行一次,或者定期重复执行. 2:TimerTask类是由 Timer 安排为一次执行或重复执行的任务 ...

  7. Java多线程19:定时器Timer

    前言 定时/计划功能在Java应用的各个领域都使用得非常多,比方说Web层面,可能一个项目要定时采集话单.定时更新某些缓存.定时清理一批不活跃用户等等.定时计划任务功能在Java中主要使用的就是Tim ...

  8. Java并发编程笔记之Timer源码分析

    timer在JDK里面,是很早的一个API了.具有延时的,并具有周期性的任务,在newScheduledThreadPool出来之前我们一般会用Timer和TimerTask来做,但是Timer存在一 ...

  9. Java定时任务:利用java Timer类实现定时执行任务的功能

    一.概述 在java中实现定时执行任务的功能,主要用到两个类,Timer和TimerTask类.其中Timer是用来在一个后台线程按指定的计划来执行指定的任务. TimerTask一个抽象类,它的子类 ...

随机推荐

  1. Hadoop-2.6.0上的C的API訪问HDFS

    在通过Hadoop-2.6.0的C的API訪问HDFS的时候,编译和执行出现了不少问题,花费了几天的时间,上网查了好多的资料,最终还是把问题给攻克了 參考文献:http://m.blog.csdn.n ...

  2. jquery07

    <!DOCTYPE HTML> <html> <head> <meta http-equiv="Content-Type" content ...

  3. android图像处理(3) 底片效果

    这篇将讲到图片特效处理的底片效果.跟前面一样是对像素点进行处理,算法是通用的. 算法原理:将当前像素点的RGB值分别与255之差后的值作为当前点的RGB值. 例: ABC 求B点的底片效果: B.r ...

  4. js -- canvas img 封装

    鼠标   1.操作canvas 中的 img. 右键放大缩小,左键移动img. 2.拖动input type= range  改变图片的透明度 html 代码 <!DOCTYPE html> ...

  5. HTTP -- 请求/响应 结构

    一:一个HTTP请求报文由四个部分组成:请求行.请求头部.空行.请求数据. 1.请求行 1.请求方法:GET POST 2.URL字段 3.HTTP版本字段 2.请求头 1.Accept:浏览器可接受 ...

  6. html --- rem 媒体查询

    rem是一种相对长度单位,参考的基准是<html>标签定义的font-size. viewport 做移动端的h5,通常会在HTML文件中指定一个<meta>标签: <m ...

  7. CSS盒子模型图

    下面这张图,是W3C标准的CSS盒子模型: 由上图可以清楚的看出各个部分的CSS属性.

  8. Cisco Works 2000 网络管理软件安装、配置全过程

    下面是在windows 2000 server 下安装ciscoworks 2000的过程.(附件中是标准avi格式文件,由于上传附件大小限制,更多内容见Sina播客) 浏览全部原创视频请见: htt ...

  9. 2017国家集训队作业[agc008f]Black Radius

    2017国家集训队作业[agc008f]Black Radius 时隔4个月,经历了省赛打酱油和中考各种被吊打后,我终于回想起了我博客园的密码= = 题意: ​ 给你一棵树,树上有若干个关键点.选中某 ...

  10. colrm---删除文件制定列