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一个抽象类,它的子类 ...
随机推荐
- 关于mysql数据库在输入password后,滴的一声直接退出界面的解决的方法(具体办法)
前一阵子.因为敲代码要用到数据库,便在本子上下载了一个,却出现非常多小问题(自己的台式机却没有该问题,可能是本人的本子太渣了吧),纠结了好一阵,回头想想.发现问题,分析问题,解决这个问题,不就是我们的 ...
- Android官方文档翻译——Fragment生命周期
网上有的博客写得太乱 不如自己翻译官方文档 Lifecycle 生命周期 Though a Fragment's lifecycle is tied to its owning activity, i ...
- 项目: 基于Python socket模块实现的简单 ftp 项目:
需要 自己创建一个 info 文件 用来存储用户信息 服务器: import socket import pickle import struct import os import time ''.s ...
- Ubuntu 12.04使用演示
今年年初,发布了Ubuntu 12.04(代号Precise Pangolin),但正式版预计将于2012年的4月底发布,作者对最新版本的ubuntu做了试用,先将操作视频与大家分享.更多内容请关注本 ...
- tcp为什么要三次握手
作者:大闲人柴毛毛链接:https://www.zhihu.com/question/24853633/answer/254224088来源:知乎著作权归作者所有.商业转载请联系作者获得授权,非商业转 ...
- django框架初探
django框架初探 1.web框架介绍 web框架本质是一个socket服务端.每一个端口只能被一个程序监听. web程序分为两个部分: 服务器程序:对socket服务器封装,解析http请求,发送 ...
- 【Codeforces Round #428 (Div. 2) B】Game of the Rows
[Link]:http://codeforces.com/contest/839/problem/B [Description] 给你n排的如题目所示的位置; 同一排中(1,2) 算相邻; (3,4) ...
- 智能指针shared_ptr, auto_ptr, scoped_ptr, weak_ptr总结
看这里: http://blog.csdn.net/lollipop_jin/article/details/8499530 shared_ptr可以多线程同时读,但是涉及到写,需要加锁. share ...
- [REASONML] Using Javascript npm package from REASON
For example, we want to use moment.js inside our ReasonML code. What we can do is create a module fi ...
- 微软推送Win10致全球网络负担增大,中国网友表示毫无压力
7月29日晚间,微软的Windows10操作系统正式上市发行.微软将面向全球190个国家地区进行windows10的免费升级推送. 眼下, Windows 10 正以疯狂的速度登陆全球各类设备 ...