Timer是一种定时器工具,用来后台线程计划执行指定任务,而TimerTask一个抽象类,它的子类代表一个可以被Timer计划的任务。
该类是线程安全的:有四个构造方法,每个构造方法都启动了计时器线程,同时Timer类可以保证多个线程可以共享单个Timer对象而无需进行外部同步。
每个Timer对象对应的是单个后台线程,用于顺序执行所有的计时器任务,一般情况下,线程任务执行所消耗的时间非常短,但由于特殊情况导致某个定时器任务执行的时间太长,那么他就会“独占”计时器的任务执行线程,其后的所有线程都必须等待它执行完,这就会延迟后续任务的执行,使这些任务堆积在一起。
一:Timer调用schedule函数,参数有以下几种情况:
schedule(TimerTask task, Date time):指定的日期时间执行指定的任务。
schedule(TimerTask task, Date firstTime, long period) :指定的任务在指定的时间开始进行重复的固定延迟执行。在firstTime开始执行任务,每period重复执行一次
schedule(TimerTask task, long delay) :延迟执行指定的任务。
schedule(TimerTask task, long delay, long period) :指定的任务从指定的延迟后,开始进行重复的固定延迟执行。延迟delay后执行一次,每period执行一次。
二:Timer调用scheduleAtFixedRate函数,参数有以下几种情况:
scheduleAtFixedRate(TimerTask task, Date firstTime, long period):指定的任务在指定的时间开始进行重复的固定速率执行。
scheduleAtFixedRate(TimerTask task, long delay, long period):指定的任务在指定的延迟后开始进行重复的固定速率执行。
三:参数TimerTask:
TimerTask类是一个抽象类,由Timer安排为一次执行或重复执行的任务。它有一个抽象方法run()方法,该方法用于执行相应计时器任务要执行的操作。因此每一个具体的任务类都必须继承TimerTask,然后重写run()方法。
另外它还有两个非抽象的方法:
boolean cancel():取消此计时器任务。
long scheduledExecutionTime():返回此任务最近实际执行的安排执行时间。
1.1:函数schedule(TimerTask task, long delay) :延迟执行指定的任务
public class TimerTest01 {
Timer timer;
public TimerTest01(int time){
timer = new Timer();
timer.schedule(new TimerTaskTest01(), time * 1000);
}
public static void main(String[] args) {
System.out.println("timer begin....");
new TimerTest01(3);
}
}
public class TimerTaskTest01 extends TimerTask{
public void run() {
System.out.println("Time's up!!!!");
}
}
打印如下:
首先打印:timer begin....
3秒后打印:Time's up!!!!
1.2 schedule(TimerTask task, Date time):指定的日期时间执行指定的任务。
public class TimerTest02 {
Timer timer;
public TimerTest02(){
Date time = getTime();
System.out.println("指定时间time=" + time);
timer = new Timer();
timer.schedule(new TimerTaskTest02(), time);
}
public Date getTime(){
Calendar calendar = Calendar.getInstance();
calendar.set(Calendar.HOUR_OF_DAY, 11);
calendar.set(Calendar.MINUTE, 39);
calendar.set(Calendar.SECOND, 00);
Date time = calendar.getTime();
return time;
}
public static void main(String[] args) {
new TimerTest02();
}
}
public class TimerTaskTest02 extends TimerTask{
@Override
public void run() {
System.out.println("指定时间执行线程任务...");
}
}
当时间到了指定的11:39:00时就会执行该线程任务,当然大于该时间也会执行!!打印如下:
指定时间time=Tue Jun 10 11:39:00 CST 2014
指定时间执行线程任务...
1.3 schedule(TimerTask task, long delay, long period) 延迟指定时间(参数2)后以指定的间隔时间(参数3)循环执行任务
public class TimerTest03 {
Timer timer;
public TimerTest03(){
timer = new Timer();
timer.schedule(new TimerTaskTest03(), 1000, 2000);
}
public static void main(String[] args) {
new TimerTest03();
}
}
public class TimerTaskTest03 extends TimerTask{
@Override
public void run() {
Date date = new Date(this.scheduledExecutionTime());
System.out.println("本次执行该线程的时间为:" + date);
}
}
执行结果:
本次执行该线程的时间为:Tue Jun 10 21:19:47 CST 2014
本次执行该线程的时间为:Tue Jun 10 21:19:49 CST 2014
本次执行该线程的时间为:Tue Jun 10 21:19:51 CST 2014
本次执行该线程的时间为:Tue Jun 10 21:19:53 CST 2014
本次执行该线程的时间为:Tue Jun 10 21:19:55 CST 2014
本次执行该线程的时间为:Tue Jun 10 21:19:57 CST 2014
.................
四:差别
1、schedule(TimerTask task, Date time)、schedule(TimerTask task, long delay)
如果当前时间已经到了或者超过计划执行的时间,则task会被立即执行。
2、schedule(TimerTask task, Date firstTime, long period)、schedule(TimerTask task, long delay, long period)
会因为前一个任务执行时间延长而延时。每一次执行的task的计划时间会随着前一个task的实际时间而发生改变,上一个任务如果耗时了,则到了时间点也不会立即执行,而是会延时执行,例如:
schedule(TimerTask task, 2000, 3000)中,在2s后执行该task,之后每隔3s执行task,按照计划第5次重复执行,应该是3*5 =15后开始执行;但如果第4次执行时耗时了,原计划立即执行,实际上花费了1s,则第五次执行顺延,变为了3*5+1=16s执行。
这两个方法更加注重保存间隔时间的稳定。
3、scheduleAtFixedRate(TimerTask task, Date firstTime, long period)、scheduleAtFixedRate(TimerTask task, long delay, long period)
这两个方法侧重于保持执行频率的稳定,不会做任何等待就会立即执行第n+1个task。
备注:以上四点,均以Timer在执行定时任务时只创建一个线程任务为例。
五:Timer的缺陷
Timer计时器可以定时(指定时间执行任务)、延迟(延迟5秒执行任务)、周期性地执行任务(每隔个1秒执行任务),但是,Timer存在一些缺陷。
1.Timer对调度的支持是基于绝对时间的,而不是相对时间,所以它对系统时间的改变非常敏感。
2.多线程任务时,需要等待前面任务完成才会后续任务。
3.Timer线程是不会捕获异常的,如果TimerTask抛出的了未检查异常则会导致Timer线程终止,同时Timer也不会重新恢复线程的执行,他会错误的认为整个Timer线程都会取消。同时,已经被安排单尚未执行的TimerTask也不会再执行了,新的任务也不能被调度。故如果TimerTask抛出未检查的异常,Timer将会产生无法预料的行为。
5.1基于绝对时间:用户调整时间,容易造成定时任务不会触发;
5.2如果存在多个线程,若其中某个线程因为某种原因而导致线程任务执行时间过长,超过了两个任务的间隔时间,会发生任务延迟。
public class TimerTest04 {
private Timer timer;
public long start;
public TimerTest04(){
this.timer = new Timer();
start = System.currentTimeMillis();
}
public void timerOne(){
timer.schedule(new TimerTask() {
public void run() {
System.out.println("timerOne invoked ,the time:" + (System.currentTimeMillis() - start));
try {
Thread.sleep(4000); //线程休眠3000
} catch (InterruptedException e) {
e.printStackTrace();
}
}
}, 1000);
}
public void timerTwo(){
timer.schedule(new TimerTask() {
public void run() {
System.out.println("timerOne invoked ,the time:" + (System.currentTimeMillis() - start));
}
}, 3000);
}
public static void main(String[] args) throws Exception {
TimerTest04 test = new TimerTest04();
test.timerOne();
test.timerTwo();
}
}
实际打印:
timerOne invoked ,the time:1000
timerOne invoked ,the time:5000
以上,timerOne由于sleep(4000),休眠了4S,同时Timer内部是一个线程,导致timeOne所需的时间超过了间隔时间。
5.3如果TimerTask抛出的了未检查异常则会导致Timer线程终止:
public class TimerTest04 {
private Timer timer;
public TimerTest04(){
this.timer = new Timer();
}
public void timerOne(){
timer.schedule(new TimerTask() {
public void run() {
throw new RuntimeException();
}
}, 1000);
}
public void timerTwo(){
timer.schedule(new TimerTask() {
public void run() {
System.out.println("我会不会执行呢??");
}
}, 1000);
}
public static void main(String[] args) {
TimerTest04 test = new TimerTest04();
test.timerOne();
test.timerTwo();
}
}
实际打印:
Exception in thread "Timer-0" java.lang.RuntimeException
at com.chenssy.timer.TimerTest04$1.run(TimerTest04.java:25)
at java.util.TimerThread.mainLoop(Timer.java:555)
at java.util.TimerThread.run(Timer.java:505)
六:解决措施
用ScheduledThreadPoolExecutor 来替代。其基于相对时间;Timer是内部是单一线程,内部是个线程池,所以可以支持多个任务并发执行。
6.1多线程并发,多线程时就算有耗时,也不会影响下一个线程的处理时间:
public class ScheduledExecutorTest {
private ScheduledExecutorService scheduExec;
public long start;
ScheduledExecutorTest(){
this.scheduExec = Executors.newScheduledThreadPool(2);
this.start = System.currentTimeMillis();
}
public void timerOne(){
scheduExec.schedule(new Runnable() {
public void run() {
System.out.println("timerOne,the time:" + (System.currentTimeMillis() - start));
try {
Thread.sleep(4000);
} catch (InterruptedException e) {
e.printStackTrace();
}
}
},1000,TimeUnit.MILLISECONDS);
}
public void timerTwo(){
scheduExec.schedule(new Runnable() {
public void run() {
System.out.println("timerTwo,the time:" + (System.currentTimeMillis() - start));
}
},2000,TimeUnit.MILLISECONDS);
}
public static void main(String[] args) {
ScheduledExecutorTest test = new ScheduledExecutorTest();
test.timerOne();
test.timerTwo();
}
}
执行结果:
timerOne,the time:1003
timerTwo,the time:2005
6.2有异常时也不会影响下一个任务
public class ScheduledExecutorTest {
private ScheduledExecutorService scheduExec;
public long start;
ScheduledExecutorTest(){
this.scheduExec = Executors.newScheduledThreadPool(2);
this.start = System.currentTimeMillis();
}
public void timerOne(){
scheduExec.schedule(new Runnable() {
public void run() {
throw new RuntimeException();
}
},1000,TimeUnit.MILLISECONDS);
}
public void timerTwo(){
scheduExec.scheduleAtFixedRate(new Runnable() {
public void run() {
System.out.println("timerTwo invoked .....");
}
},2000,500,TimeUnit.MILLISECONDS);
}
public static void main(String[] args) {
ScheduledExecutorTest test = new ScheduledExecutorTest();
test.timerOne();
test.timerTwo();
}
}
执行结果:
timerTwo invoked .....
timerTwo invoked .....
timerTwo invoked .....
timerTwo invoked .....
timerTwo invoked .....
timerTwo invoked .....
timerTwo invoked .....
timerTwo invoked .....
timerTwo invoked .....
........................
最后:
一般用来做临时定时器,可以选择Timer,但是在时间容易变动的设备上,不推荐此函数。
文章中举例,大多数是用单线程,即一个Timer,执行一个task。
Timer的保存间隔时间的稳定和保持执行频率的稳定,都是针对单线程。