Java Timer TimerTask Example(java Timer的例子)
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.
Thread Life Cycle in Java – Thread States in Java
Java Thread Dump – VisualVM, jstack, kill -3, jcmd
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 Timer TimerTask Example(java Timer的例子)的更多相关文章
- JAVA中的定时调度(Timer和TimerTask)
某些时候我们需要定时去完成一些任务,这里举一个例子:我们需要在3秒钟后打印当前系统时间,此后每隔5秒重复此操作.代码如下: import java.util.TimerTask; import jav ...
- Java 工具类 —— 定时器(Timer/TimerTask)
import java.util.Timer; import java.util.TimerTask; public class Timer { .... public void schedule(T ...
- 几种任务调度的 Java 实现方法与比较Timer,ScheduledExecutor,Quartz,JCronTab
几种任务调度的 Java 实现方法与比较 综观目前的 Web 应用,多数应用都具备任务调度的功能.本文由浅入深介绍了几种任务调度的 Java 实现方法,包括 Timer,Scheduler, Quar ...
- JDK Timer & TimerTask
目录 Timer & TimerTask Binary Heap Insert DELETE MIN PERFORMANCE LifeCycle Constructor MainLoop sc ...
- Java Timer, TimerTask, Timer.Schedule
schedule的意思(时间表.进度表) timer.schedule(new TimerTask(){ void run()},0, 60*60*1000);timer.schedule(new M ...
- Java定时器Timer,TimerTask每隔一段时间随机生成数字
1:java.util.Timer类是一种工具,线程用其安排以后在后台线程中执行的任务.可安排任务执行一次,或者定期重复执行. 2:TimerTask类是由 Timer 安排为一次执行或重复执行的任务 ...
- Java多线程19:定时器Timer
前言 定时/计划功能在Java应用的各个领域都使用得非常多,比方说Web层面,可能一个项目要定时采集话单.定时更新某些缓存.定时清理一批不活跃用户等等.定时计划任务功能在Java中主要使用的就是Tim ...
- Java并发编程笔记之Timer源码分析
timer在JDK里面,是很早的一个API了.具有延时的,并具有周期性的任务,在newScheduledThreadPool出来之前我们一般会用Timer和TimerTask来做,但是Timer存在一 ...
- Java定时任务:利用java Timer类实现定时执行任务的功能
一.概述 在java中实现定时执行任务的功能,主要用到两个类,Timer和TimerTask类.其中Timer是用来在一个后台线程按指定的计划来执行指定的任务. TimerTask一个抽象类,它的子类 ...
随机推荐
- session timer(一)
功能介绍 SIP并没有为所建立的会话定义存活机制. 虽然用户代理能够通过会话特定的机制推断会话是否超时,可是代理server却做不到这点. 如此一来.代理server有时会无法推断会话是否还是活动的. ...
- Linux 时区的修改
Linux 时区的修改 1. CentOS和Ubuntu的时区文件是/etc/localtime,但是在CentOS7以后localtime以及变成了一个链接文件 ``` [root@centos7 ...
- Git学习总结(2)——初识 GitHub
1. 写在前面 我一直认为 GitHub 是程序员必备技能,程序员应该没有不知道 GitHub 的才对,没想到这两天留言里给我留言最多的就是想让我写关于 GitHub 的教程,说看了不少资料还是一头雾 ...
- Tomcat之虚拟主机配置以及web应用配置
Tomcat之虚拟主机配置以及web应用配置 Tomcat文件夹结构例如以下: bin ---- 启动和关闭须要的bat文件所在的文件夹 conf --- 配置文件夹 lib --- tomcat执 ...
- [51Nod]NOIP2018提高组省一冲奖班模测训练(一)题解
http://www.51nod.com/contest/problemList.html#!contestId=72&randomCode=147206 原题水题大赛.. A.珂朵莉的旅行 ...
- php实现遍历文件目录
php实现遍历文件目录 一.总结 1.熟悉简单:很经典的例子,多看,然后发现熟悉了很简单 二.php实现遍历目录 php实现遍历目录 代码一: //遍历目录 function iteral($path ...
- Android自定义系统分享面板
在Android中实现分享有一种比较方便的方式,调用系统的分享面板来分享我们的应用.最基本的实现如下: public Intent getShareIntent(){ Intent intent = ...
- js 关于网易淘宝移动端适配的学习
(function (doc, win) { // orientationchange:用户水平或者垂直翻转设备(即方向发生变化)时触发的事件;(屏幕大小发生变化) var docEl = doc.d ...
- JS学习笔记 - Try / Catch / Finally
<body> <p>请输入 5 和 10 之间的一个数:</p> <input id="demo" type="text&quo ...
- 七、Docker+nginx
原文:七.Docker+nginx docker run -p 80:80 --name nginx-v1.0.0 -v /usr/nginx/www:/www -v /home/docker/ngi ...