您的位置:首页 > 编程语言 > Java开发

具体解释java定时任务

2015-12-29 21:03 621 查看
在我们编程过程中假设须要运行一些简单的定时任务,无须做复杂的控制。我们能够考虑使用JDK中的Timer定时任务来实现。

以下LZ就其原理、实例以及Timer缺陷三个方面来解析java Timer定时器。

一、简单介绍

在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():返回此任务近期实际运行的安排运行时间。

二、实例

2.1、指定延迟时间运行定时任务

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!!!!


2.2、在指定时间运行定时任务

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
指定时间运行线程任务...


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
.................


对于这个线程任务,假设我们不将该任务停止,他会一直运行下去。

对于上面三个实例,LZ仅仅是简单的演示了一下。同一时候也没有解说scheduleAtFixedRate方法的样例,事实上该方法与schedule方法一样。

2.4、分析schedule和scheduleAtFixedRate

1、schedule(TimerTask task, Date time)、schedule(TimerTask task, long delay)

对于这两个方法而言,假设指定的计划运行时间scheduledExecutionTime<= systemCurrentTime,则task会被马上运行。

scheduledExecutionTime不会由于某一个task的过度运行而改变。

2、schedule(TimerTask task, Date firstTime, long period)、schedule(TimerTask task, long delay, long period)

这两个方法与上面两个就有点儿不同的,前面提过Timer的计时器任务会由于前一个任务运行时间较长而延时。在这两个方法中,每一次运行的task的计划时间会随着前一个task的实际时间而发生改变,也就是scheduledExecutionTime(n+1)=realExecutionTime(n)+periodTime。也就是说假设第n个task由于某种情况导致这次的运行时间过程,最后导致systemCurrentTime>= scheduledExecutionTime(n+1),这是第n+1个task并不会由于到时了而运行,他会等待第n个task运行完之后再运行,那么这样势必会导致n+2个的运行实现scheduledExecutionTime放生改变即scheduledExecutionTime(n+2) = realExecutionTime(n+1)+periodTime。所以这两个方法更加注重保存间隔时间的稳定。

3、scheduleAtFixedRate(TimerTask task, Date firstTime, long period)、scheduleAtFixedRate(TimerTask task, long delay, long period)

在前面也提过scheduleAtFixedRate与schedule方法的側重点不同,schedule方法側重保存间隔时间的稳定,而scheduleAtFixedRate方法更加側重于保持运行频率的稳定。为什么这么说,原因例如以下。

在schedule方法中会由于前一个任务的延迟而导致其后面的定时任务延时,而scheduleAtFixedRate方法则不会。假设第n个task运行时间过长导致systemCurrentTime>= scheduledExecutionTime(n+1),则不会做不论什么等待他会马上运行第n+1个task,所以scheduleAtFixedRate方法运行时间的计算方法不同于schedule,而是scheduledExecutionTime(n)=firstExecuteTime +n*periodTime,该计算方法永远保持不变。

所以scheduleAtFixedRate更加側重于保持运行频率的稳定。

三、Timer的缺陷

3.1、Timer的缺陷

Timer计时器能够定时(指定时间运行任务)、延迟(延迟5秒运行任务)、周期性地运行任务(每隔个1秒运行任务),可是,Timer存在一些缺陷。

首先Timer对调度的支持是基于绝对时间的,而不是相对时间。所以它对系统时间的改变很敏感。其次Timer线程是不会捕获异常的,假设TimerTask抛出的了未检查异常则会导致Timer线程终止。同一时候Timer也不会又一次恢复线程的运行,他会错误的觉得整个Timer线程都会取消。同一时候。已经被安排单尚未运行的TimerTask也不会再运行了,新的任务也不能被调度。故假设TimerTask抛出未检查的异常。Timer将会产生无法预料的行为。

1、Timer管理时间延迟缺陷

前面Timer在运行定时任务时仅仅会创建一个线程任务,假设存在多个线程,若当中某个线程由于某种原因而导致线程任务运行时间过长,超过了两个任务的间隔时间。会发生一些缺陷:

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();
}
}


依照我们正常思路,timerTwo应该是在3s后运行,其结果应该是:

timerOne invoked ,the time:1001
timerOne invoked ,the time:3001


可是事与愿违,timerOne由于sleep(4000),休眠了4S。同一时候Timer内部是一个线程。导致timeOne所需的时间超过了间隔时间。结果:

timerOne invoked ,the time:1000
timerOne invoked ,the time:5000


2、Timer抛出异常缺陷

假设TimerTask抛出RuntimeException,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();
}
}


运行结果:timerOne抛出异常,导致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)


对于Timer的缺陷,我们能够考虑 ScheduledThreadPoolExecutor 来替代。Timer是基于绝对时间的。对系统时间比較敏感。而ScheduledThreadPoolExecutor 则是基于相对时间;Timer是内部是单一线程,而ScheduledThreadPoolExecutor内部是个线程池,所以能够支持多个任务并发运行。

3.2、用ScheduledExecutorService替代Timer

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


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 .....
........................


--------------------------------------------------------------------------------------------------------------------------------------------------------

原文出自:http://cmsblogs.com/?p=1175

尊重作者的成果,转载请注明出处!

个人网站:http://cmsblogs.com
--------------------------------------------------------------------------------------------------------------------------------------------------------
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: