Java定时任务
参考博文:https://www.cnblogs.com/chenssy/p/3788407.html
在我们编程过程中如果需要执行一些简单的定时任务,无须做复杂的控制,我们可以考虑使用JDK1.3诞生的 Timer 定时任务类来实现。下面就其原理、实例以及Timer缺陷三个方面介绍java Timer定时器。
一、简介
在java中一个完整定时任务需要由Timer、TimerTask两个类来配合完成。Timer和TimerTask都在java.util包内, API中是这样定义他们的。
Timer:一种工具,线程用其安排以后在后台线程中执行的任务。可安排任务执行一次,或者定期重复执行。
TimerTask:Timer 安排为一次执行或重复执行的任务。
我们可以这样理解:Timer 是一种定时器工具,用来在一个后台线程计划执行指定任务,而TimerTask一个抽象类,它的子类代表一个可以被 Timer 所计划的任务。
1、Timer类
继承关系及类声明:
java.lang.Object
|____java.util.Timer
package java.util;
/**
* @author Josh Bloch
* @see TimerTask
* @see Object#wait(long)
* @since 1.3
*/
public class Timer {
private final TaskQueue queue = new TaskQueue();
private final TimerThread thread = new TimerThread(queue);
}
从类声明上可以看出,Timer 类中创建了一个任务队列和一个定时器线程,在定时器线程中传入任务队列。
构造方法:
Timer 定时器工具类给我们提供了四个构造方法:
public Timer() {
this("Timer-" + serialNumber());
}
public Timer(boolean isDaemon) {
this("Timer-" + serialNumber(), isDaemon);
}
public Timer(String name) {
thread.setName(name);
thread.start();
}
public Timer(String name, boolean isDaemon) {
thread.setName(name);
thread.setDaemon(isDaemon);
thread.start();
}
这四个构造方法都启动了计时器线程,
private final TimerThread thread = new TimerThread(queue);
同时 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) | 安排指定的任务在指定的延迟后开始进行重复的固定速率执行 |
2、TimerTask
TimerTask类是一个抽象类,由Timer 安排为一次执行或重复执行的任务。它有一个抽象方法run()方法,该方法用于执行相应计时器任务要执行的操作。因此每一个具体的任务类都必须继承TimerTask,然后重写run()方法。
继承关系和类声明:
java.lang.Object
|____java.util.TimerTask
package java.util;
/**
* @author Josh Bloch
* @see Timer
* @since 1.3
*/
public abstract class TimerTask implements Runnable {}
另外它还有两个非抽象的方法:
boolean cancel() | 取消此计时器任务。 |
long scheduledExecutionTime() | 返回此任务最近实际执行的安排执行时间。 |
二、示例
1、指定延迟时间执行定时任务
MyTimer:
package basis.stuTimer;
import java.util.Date;
import java.util.TimerTask;
public class MyTimer extends TimerTask {
@Override
public void run() {
System.out.println("MyTimer 提醒您,现在时间是:"+new Date(System.currentTimeMillis()).toLocaleString());
}
}
测试类:
package basis.stuTimer;
import java.util.Timer;
public class TestTimer {
Timer timer;
public TestTimer(int delayTime){
timer = new Timer();
timer.schedule(new MyTimer(),delayTime);
}
public static void main(String[] args) {
System.out.println("timer begin...");
new TestTimer(5000);
}
}
运行结果:
timer begin...
MyTimer 提醒您,现在时间是:2019-8-13 9:04:39
2、在指定时间执行定时任务
MyTimer类不变。
测试类:
package basis.stuTimer;
import java.util.Calendar;
import java.util.Date;
import java.util.Timer;
public class TestTimer_1 {
Timer timer;
public static void main(String[] args) {
new TestTimer_1();
}
public TestTimer_1(){
Date time = getTime();
System.out.println("指定时间:"+time);
timer = new Timer();
timer.schedule(new MyTimer(),time);
}
public Date getTime(){
Calendar calendar = Calendar.getInstance();
calendar.set(Calendar.HOUR_OF_DAY,9);
calendar.set(Calendar.MINUTE,18);
calendar.set(Calendar.SECOND,00);
return calendar.getTime();
}
}
如果Data是一个过去的时间或者时间突然跳到设置时间点之后,那么定时任务会立即执行。
3、在延迟指定时间后以指定的时间间隔循环执行定时任务
MyTimer类不变。
测试类:
package basis.stuTimer;
import java.util.Timer;
public class TestTimer_2 {
Timer timer;
public TestTimer_2(){
timer = new Timer();
//延迟10秒后,开始每3秒循环执行
timer.schedule(new MyTimer(),10000,3000);
}
public static void main(String[] args) {
new TestTimer_2();
}
}
结果:
MyTimer 提醒您,现在时间是:2019-8-13 9:24:47
MyTimer 提醒您,现在时间是:2019-8-13 9:24:50
MyTimer 提醒您,现在时间是:2019-8-13 9:24:53
MyTimer 提醒您,现在时间是:2019-8-13 9:24:56
该定时任务在c程序启动10秒后,开始每3秒执行一次。如果我们不停止,会一直执行下去。
三、分析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,而是s cheduledExecutionTime(n)=firstExecuteTime +n*periodTime,该计算方法永远保持不变。所以scheduleAtFixedRate更加侧重于保持执行频率的稳定。
四、Timer的缺陷
Timer计时器可以定时(指定时间点执行任务)、延迟(延迟指定时间执行任务)、周期性地执行任务(每隔指定时间执行任务),但是,Timer存在一些缺陷:
- 首先Timer对调度的支持是基于绝对时间的,而不是相对时间,所以它对系统时间的改变非常敏感。
- 其次Timer线程是不会捕获异常的,如果TimerTask抛出的了未检查异常则会导致Timer线程终止,同时Timer也不会重新恢复线程的执行,他会错误的认为整个Timer线程都会取消。同时,已经被安排但尚未执行的TimerTask也不会再执行了,新的任务也不能被调度。故如果TimerTask抛出未检查的异常,Timer将会产生无法预料的行为。
1、多任务Timer延迟
Timer在执行定时任务时只会创建一个线程任务,如果存在多个线程,若其中某个线程因为某种原因而导致线程任务执行时间过长,超过了两个任务的间隔时间,会导致后一个任务不能按时开始:
package basis.stuTimer;
import java.util.Timer;
import java.util.TimerTask;
public class TestTimer_3 {
private Timer timer;
public long start;
public TestTimer_3(){
this.timer = new Timer();
start = System.currentTimeMillis();
}
public void timerOne(){
timer.schedule(new TimerTask() {
@Override
public void run() {
System.out.println("timerOne invoked ,the time:" + (System.currentTimeMillis() - start));
try {
Thread.sleep(3000); //线程休眠5000
} catch (InterruptedException e) {
e.printStackTrace();
}
}
},1000);
}
public void timerTwo(){
timer.schedule(new TimerTask() {
@Override
public void run() {
System.out.println("timerOne invoked ,the time:" + (System.currentTimeMillis() - start));
}
},3000);
}
public static void main(String[] args) {
TestTimer_3 testTimer_3 = new TestTimer_3();
testTimer_3.timerOne();
testTimer_3.timerTwo();
}
}
输出结果:
timerOne invoked ,the time:1010
timerOne invoked ,the time:6010
可以看出,timerTwo 并没有在 程序启动3000毫秒后开始执行,而是在timerTwo在Timer中执行完成后(此时已经过了3000毫秒)立即开始执行。
2、多任务异常终止
如果多个任务在 一个Timer 中执行,如果其中一个异常终止,那么该异常终止任务之后的任务也得不到执行:
package basis.stuTimer;
import java.util.Timer;
import java.util.TimerTask;
public class TestTimer_4 {
private Timer timer;
public long start;
public TestTimer_4(){
this.timer = new Timer();
start = System.currentTimeMillis();
}
public void timerOne(){
timer.schedule(new TimerTask() {
@Override
public void run() {
throw new RuntimeException();
}
},1000);
}
public void timerTwo(){
timer.schedule(new TimerTask() {
@Override
public void run() {
System.out.println("我会不会执行呢?");
}
},2000);
}
public static void main(String[] args) {
TestTimer_4 testTimer_4 = new TestTimer_4();
testTimer_4.timerOne();
testTimer_4.timerTwo();
}
}
运行结果:
Exception in thread "Timer-0" java.lang.RuntimeException
at basis.stuTimer.TestTimer_4$1.run(TestTimer_4.java:19)
at java.util.TimerThread.mainLoop(Timer.java:555)
at java.util.TimerThread.run(Timer.java:505)
可以看出,由于teskOne异常终止,而导致TaskTwo 也不能执行。
五、使用scheduleExecutorService替代Timer避免缺陷
1、解决多任务Timer延迟
代码:
package basis.stuScheduledExecutor;
import java.util.concurrent.Executors;
import java.util.concurrent.ScheduledExecutorService;
import java.util.concurrent.TimeUnit;
public class TestScheduledExecutor {
private ScheduledExecutorService scheduleExec;
public long start;
public TestScheduledExecutor(){
this.scheduleExec = Executors.newScheduledThreadPool(2);
this.start = System.currentTimeMillis();
}
public void timerOne(){
scheduleExec.schedule(new Runnable() {
@Override
public void run() {
System.out.println("timerOne,the time:"+(System.currentTimeMillis()-start));
try {
//TimeUnit.SECONDS.sleep(4);
Thread.sleep(4000);
} catch (InterruptedException e) {
e.printStackTrace();
}
}
},1000, TimeUnit.MILLISECONDS);
}
public void timeTwo(){
scheduleExec.schedule(new Runnable() {
@Override
public void run() {
System.out.println("timeTwo,the time:"+(System.currentTimeMillis()-start));
}
},2000,TimeUnit.MILLISECONDS);
}
public static void main(String[] args) {
TestScheduledExecutor test = new TestScheduledExecutor();
test.timerOne();
test.timeTwo();
}
}
结果:
timerOne,the time:1010
timeTwo,the time:2020
由结果可以看出,timerOne 任务的休眠,并不能影响timerTwo任务的按时开始。
2、解决多任务异常终止
代码:
package basis.stuScheduledExecutor;
import java.util.concurrent.Executors;
import java.util.concurrent.ScheduledExecutorService;
import java.util.concurrent.TimeUnit;
public class TestScheduledExecutor_1 {
private ScheduledExecutorService scheduleExec;
public long start;
public TestScheduledExecutor_1(){
this.scheduleExec = Executors.newScheduledThreadPool(2);
this.start = System.currentTimeMillis();
}
public void timerOne(){
scheduleExec.schedule(new Runnable() {
@Override
public void run() {
throw new RuntimeException();
}
},1000, TimeUnit.MILLISECONDS);
}
public void timeTwo(){
scheduleExec.schedule(new Runnable() {
@Override
public void run() {
System.out.println("timeTwo invoked...");
}
},2000,TimeUnit.MILLISECONDS);
}
public static void main(String[] args) {
TestScheduledExecutor_1 test = new TestScheduledExecutor_1();
test.timerOne();
test.timeTwo();
}
}
结果:
timeTwo invoked...
由结果可以看出,尽管再同一个Timer中的timerOne被异常中断,依旧不影响timerTwo的按时执行。