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一个抽象类,它的子类 ...
随机推荐
- [Python] Generates permutations
>>> import itertools >>> for p in itertools.permutations('ABCD'): ... print(p) ('A ...
- SQL事务+异常
BEGIN TRAN BEGIN TRY --这里写代码 --这里写代码 END TRY BEGIN CATCH ROLLBACK TRAN END CATCH COMMIT TRAN
- CentOS6.5下的Nagios安装配置详解(图文)
最近因为,科研需要,接触上了Nagios,这里,我将安装笔记做个详解.为自己后续需要和博友们学习! VMware workstation 11 的下载 VMWare Workstation 11的安装 ...
- 微信小程序---app.json中设置背景色不生效解决办法
按照官方文档的说明,backgroundColor应该可以设置窗口的背景色. "window":{ "backgroundTextStyle":"li ...
- linux新安装后root密码设置
linux在安装过程中未设置root密码 导致在使用中无法su 解决方法是设置root密码: 输入: sudo passwd root [sudo] password for you: ---> ...
- java 参数
-Xmx:size java最大堆内存 -Xms:size 初始化内存 -Xmn:size 年轻带堆大小 -XX:NewSize=size 年轻带的大小 -XX:NewRatio=ratio 年轻带和 ...
- Matlab piecelin
function v = piecelin(x,y,u) %PIECELIN Piecewise linear interpolation. % v = piecelin(x,y,u) finds t ...
- jquery constructor
function F(){ this.a = "aaa"; alert(111); } F.prototype = { constructor:F, } var f = new F ...
- worktools-git 工具的使用总结(2)
1.创建分支 git branch son parent //创建分支,是在master 分支的基础上创建 :~/myGit$ git st # On branch master nothing to ...
- 很好的资源 for android
//texttospeach http://examples.javacodegeeks.com/android/core/text-to-speech/android-text-to-speech- ...