详解java定时任务

在java中一个完整定时任务需要由Timer、TimerTask两个类来配合完成。 API中是这样定义他们的,Timer:一种工具,线程用其安排以后在后台线程中执行的任务。可安排任务执行一次,或者定期重复执行。由TimerTask:Timer 安排为一次执行或重复执行的任务。我们可以这样理解Timer是一种定时器工具,用来在一个后台线程计划执行指定任务,而TimerTask一个抽象类,它的子类代表一个可以被Timer计划的任务。

Timer类

在工具类Timer中,提供了四个构造方法,每个构造方法都启动了计时器线程,同时Timer类可以保证多个线程可以共享单个Timer对象而无需进行外部同步,所以Timer类是线程安全的。但是由于每一个Timer对象对应的是单个后台线程,用于顺序执行所有的计时器任务,一般情况下我们的线程任务执行所消耗的时间应该非常短,但是由于特殊情况导致某个定时器任务执行的时间太长,那么他就会“独占”计时器的任务执行线程,其后的所有线程都必须等待它执行完,这就会延迟后续任务的执行,使这些任务堆积在一起,具体情况我们后面分析。

当程序初始化完成Timer后,定时任务就会按照我们设定的时间去执行,Timer提供了schedule方法,该方法有多中重载方式来适应不同的情况,如下:

schedule(TimerTask task, Date time):安排在指定的时间执行指定的任务。

schedule(TimerTask task, Date firstTime, long period) :安排指定的任务在指定的时间开始进行重复的固定延迟执行。

schedule(TimerTask task, long delay) :安排在指定延迟后执行指定的任务。

schedule(TimerTask task, long delay, long period) :安排指定的任务从指定的延迟后开始进行重复的固定延迟执行。

同时也重载了scheduleAtFixedRate方法,scheduleAtFixedRate方法与schedule相同,只不过他们的侧重点不同,区别后面分析。

scheduleAtFixedRate(TimerTask task, Date firstTime, long period):安排指定的任务在指定的时间开始进行重复的固定速率执行。

scheduleAtFixedRate(TimerTask task, long delay, long period):安排指定的任务在指定的延迟后开始进行重复的固定速率执行。

TimerTask

TimerTask类是一个抽象类,由Timer 安排为一次执行或重复执行的任务。它有一个抽象方法run()方法,该方法用于执行相应计时器任务要执行的操作。因此每一个具体的任务类都必须继承TimerTask,然后重写run()方法。

另外它还有两个非抽象的方法:

boolean cancel():取消此计时器任务。

long scheduledExecutionTime():返回此任务最近实际执行的安排执行时间。

Timer的缺陷

Timer计时器可以定时(指定时间执行任务)、延迟(延迟5秒执行任务)、周期性地执行任务(每隔个1秒执行任务),但是,Timer存在一些缺陷。首先Timer对调度的支持是基于绝对时间的,而不是相对时间,所以它对系统时间的改变非常敏感。其次Timer线程是不会捕获异常的,如果TimerTask抛出的了未检查异常则会导致Timer线程终止,同时Timer也不会重新恢复线程的执行,他会错误的认为整个Timer线程都会取消。同时,已经被安排单尚未执行的TimerTask也不会再执行了,新的任务也不能被调度。故如果TimerTask抛出未检查的异常,Timer将会产生无法预料的行为。

1、Timer管理时间延迟缺陷

前面Timer在执行定时任务时只会创建一个线程任务,如果存在多个线程,若其中某个线程因为某种原因而导致线程任务执行时间过长,超过了两个任务的间隔时间,会发生一些缺陷:

 1 package springBootExample.example.TestSource;
 2 
 3 import java.util.Calendar;
 4 import java.util.Date;
 5 import java.util.Timer;
 6 import java.util.TimerTask;
 7 import java.util.concurrent.Executors;
 8 import java.util.concurrent.ScheduledExecutorService;
 9 import java.util.concurrent.TimeUnit;
10 
11 public class TimerTest {
12     
13     private Timer timer;
14     private  ScheduledExecutorService scheduExec;
15     public TimerTest(){
16         timer = new Timer();
17         scheduExec = Executors.newScheduledThreadPool(2);
18     }57         public void timerThree(){
58             timer.schedule(new TimerTask(){
59                 public void run(){
60                     try {
61                         System.out.println("timerThree invoked ,the time:"+System.currentTimeMillis());
62                         Thread.sleep(5000);
63                     } catch (InterruptedException e) {
64                         e.printStackTrace();
65                         System.out.println("timerThree 发生异常了");
66                     }
67                     
68                 }
69             }, 1000);
70         }
71         
72         public void timerFour(){
73             timer.schedule(new TimerTask(){
74                 public void run(){
75                     System.out.println("timerFour invoked , the time:"+System.currentTimeMillis());
76                 }
77             }, 3000);
78         }
79      
80     
81     public static void main(String args[]){
82         TimerTest timer = new TimerTest();
83         timer.timerThree();
84         timer.timerFour();
85         //timer.timerOne();
86         //timer.timerTwo();
87     }
88     
89 
90 }

输出结果:

1 timerThree invoked ,the time:1503135317852
2 timerFour invoked , the time:1503135322853

有5秒的延迟,而不是三秒,说明在timer中有时间延迟缺陷

2、Timer抛出异常缺陷

 1 public class TimerTest {
 2     
 3     private Timer timer;
 4     private  ScheduledExecutorService scheduExec;
 5     public TimerTest(){
 6         timer = new Timer();
 7         scheduExec = Executors.newScheduledThreadPool(2);
 8     }
 9     public void testTimer(){
10         Date date = getTime();
11         timer.schedule(new MyTimetask(), date);
12     }
13     47         public void timerThree(){
48             timer.schedule(new TimerTask(){
49                 public void run(){
50                     try {
51                         System.out.println("timerThree invoked ,the time:"+System.currentTimeMillis());
52                         Thread.sleep(5000);
                throw new RuntimeException ("运行时异常");
53 } catch (InterruptedException e) { 54 e.printStackTrace(); 55 System.out.println("timerThree 发生异常了"); 56 } 57 58 } 59 }, 1000); 60 } 61 62 public void timerFour(){ 63 timer.schedule(new TimerTask(){ 64 public void run(){ 65 System.out.println("timerFour invoked , the time:"+System.currentTimeMillis()); 66 } 67 }, 3000); 68 } 69 70 71 public static void main(String args[]){ 72 TimerTest timer = new TimerTest(); 73 timer.timerThree(); 74 timer.timerFour(); 75 //timer.timerOne(); 76 //timer.timerTwo(); 77 } 78 79 80 }

输出结果:

1 timerThree invoked ,the time:1503135540831
2 Exception in thread "Timer-0" java.lang.RuntimeException: 运行时异常
3     at springBootExample.example.TestSource.TimerTest$3.run(TimerTest.java:63)
4     at java.util.TimerThread.mainLoop(Timer.java:555)
5     at java.util.TimerThread.run(Timer.java:505)

后面的任务4将不再执行。。。。。

解决办法以上两种缺陷的办法:

用ScheduledExecutorService替代Timer可以解决以上两种缺陷:

 1 public class TimerTest {
 2     
 3     private Timer timer;
 4     private  ScheduledExecutorService scheduExec;
 5     public TimerTest(){
 6         timer = new Timer();
 7         scheduExec = Executors.newScheduledThreadPool(2);
 8     }
 9     public void testTimer(){
10         Date date = getTime();
11         timer.schedule(new MyTimetask(), date);
12     }
13     22           
23      
24      public void timerOne(){
25          scheduExec.schedule(new Runnable() {
26                 public void run() {
27                     System.out.println("timerOne invoked ,the time:" + System.currentTimeMillis());
28                     try {
29                         Thread.sleep(4000); 
30                         throw new RuntimeException();//线程休眠3000
31                     } catch (InterruptedException e) {
32                         //e.printStackTrace();
33                     }finally{
34                         System.out.println("timerOne 发生异常了");
35                     }
36                 }
37             }, 1000,TimeUnit.MILLISECONDS);
38         }
39         
40         public void timerTwo(){
41             scheduExec.schedule(new Runnable() {
42                 public void run() {
43                     System.out.println("timertwo invoked ,the time:" + System.currentTimeMillis());
44                 }
45             }, 3000,TimeUnit.MILLISECONDS);
46         }
47    70      
71     
72     public static void main(String args[]){
73         TimerTest timer = new TimerTest();
74         //timer.timerThree();
75         //timer.timerFour();
76         timer.timerOne();
77         timer.timerTwo();
78     }
79     
80 
81 }

运行结果:

timerOne invoked ,the time:1503135797795
timertwo invoked ,the time:1503135799795
timerOne 发生异常了

从结果看two只延迟了2秒,将two延迟到one发生异常后再执行,结果是:

timerOne invoked ,the time:1503135927246
timerOne 发生异常了
timertwo invoked ,the time:1503135932246

异常不会影响two任务。

reference:

[1] :http://cmsblogs.com/?p=1175

原文地址:https://www.cnblogs.com/hoojjack/p/7397392.html