在我们编程过程中如果需要执行一些简单的定时任务,无须做复杂的控制,我们可以考虑使用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、指定延迟时间执行定时任务

  1. public class TimerTest01 {
  2. Timer timer;
  3. public TimerTest01(int time){
  4. timer = new Timer();
  5. timer.schedule(new TimerTaskTest01(), time * 1000);
  6. }
  7. public static void main(String[] args) {
  8. System.out.println("timer begin....");
  9. new TimerTest01(3);
  10. }
  11. }
  12. public class TimerTaskTest01 extends TimerTask{
  13. public void run() {
  14. System.out.println("Time's up!!!!");
  15. }
  16. }

运行结果:

  1. 首先打印:timer begin....
  2. 3秒后打印:Time's up!!!!

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

  1. public class TimerTest02 {
  2. Timer timer;
  3. public TimerTest02(){
  4. Date time = getTime();
  5. System.out.println("指定时间time=" + time);
  6. timer = new Timer();
  7. timer.schedule(new TimerTaskTest02(), time);
  8. }
  9. public Date getTime(){
  10. Calendar calendar = Calendar.getInstance();
  11. calendar.set(Calendar.HOUR_OF_DAY, 11);
  12. calendar.set(Calendar.MINUTE, 39);
  13. calendar.set(Calendar.SECOND, 00);
  14. Date time = calendar.getTime();
  15. return time;
  16. }
  17. public static void main(String[] args) {
  18. new TimerTest02();
  19. }
  20. }
  21. public class TimerTaskTest02 extends TimerTask{
  22. @Override
  23. public void run() {
  24. System.out.println("指定时间执行线程任务...");
  25. }
  26. }

当时间到达11:39:00时就会执行该线程任务,当然大于该时间也会执行!!执行结果为:

  1. 指定时间time=Tue Jun 10 11:39:00 CST 2014
  2. 指定时间执行线程任务...

2.3、在延迟指定时间后以指定的间隔时间循环执行定时任务

  1. public class TimerTest03 {
  2. Timer timer;
  3. public TimerTest03(){
  4. timer = new Timer();
  5. timer.schedule(new TimerTaskTest03(), 1000, 2000);
  6. }
  7. public static void main(String[] args) {
  8. new TimerTest03();
  9. }
  10. }
  11. public class TimerTaskTest03 extends TimerTask{
  12. @Override
  13. public void run() {
  14. Date date = new Date(this.scheduledExecutionTime());
  15. System.out.println("本次执行该线程的时间为:" + date);
  16. }
  17. }

运行结果:

  1. 本次执行该线程的时间为:Tue Jun 10 21:19:47 CST 2014
  2. 本次执行该线程的时间为:Tue Jun 10 21:19:49 CST 2014
  3. 本次执行该线程的时间为:Tue Jun 10 21:19:51 CST 2014
  4. 本次执行该线程的时间为:Tue Jun 10 21:19:53 CST 2014
  5. 本次执行该线程的时间为:Tue Jun 10 21:19:55 CST 2014
  6. 本次执行该线程的时间为:Tue Jun 10 21:19:57 CST 2014
  7. .................

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

对于上面三个实例,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在执行定时任务时只会创建一个线程任务,如果存在多个线程,若其中某个线程因为某种原因而导致线程任务执行时间过长,超过了两个任务的间隔时间,会发生一些缺陷:

  1. public class TimerTest04 {
  2. private Timer timer;
  3. public long start;
  4. public TimerTest04(){
  5. this.timer = new Timer();
  6. start = System.currentTimeMillis();
  7. }
  8. public void timerOne(){
  9. timer.schedule(new TimerTask() {
  10. public void run() {
  11. System.out.println("timerOne invoked ,the time:" + (System.currentTimeMillis() - start));
  12. try {
  13. Thread.sleep(4000);    //线程休眠3000
  14. } catch (InterruptedException e) {
  15. e.printStackTrace();
  16. }
  17. }
  18. }, 1000);
  19. }
  20. public void timerTwo(){
  21. timer.schedule(new TimerTask() {
  22. public void run() {
  23. System.out.println("timerOne invoked ,the time:" + (System.currentTimeMillis() - start));
  24. }
  25. }, 3000);
  26. }
  27. public static void main(String[] args) throws Exception {
  28. TimerTest04 test = new TimerTest04();
  29. test.timerOne();
  30. test.timerTwo();
  31. }
  32. }

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

  1. timerOne invoked ,the time:1001
  2. timerOne invoked ,the time:3001

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

  1. timerOne invoked ,the time:1000
  2. timerOne invoked ,the time:5000

      2、Timer抛出异常缺陷

如果TimerTask抛出RuntimeException,Timer会终止所有任务的运行。如下:

  1. public class TimerTest04 {
  2. private Timer timer;
  3. public TimerTest04(){
  4. this.timer = new Timer();
  5. }
  6. public void timerOne(){
  7. timer.schedule(new TimerTask() {
  8. public void run() {
  9. throw new RuntimeException();
  10. }
  11. }, 1000);
  12. }
  13. public void timerTwo(){
  14. timer.schedule(new TimerTask() {
  15. public void run() {
  16. System.out.println("我会不会执行呢??");
  17. }
  18. }, 1000);
  19. }
  20. public static void main(String[] args) {
  21. TimerTest04 test = new TimerTest04();
  22. test.timerOne();
  23. test.timerTwo();
  24. }
  25. }

运行结果:timerOne抛出异常,导致timerTwo任务终止。

  1. Exception in thread "Timer-0" java.lang.RuntimeException
  2. at com.chenssy.timer.TimerTest04$1.run(TimerTest04.java:25)
  3. at java.util.TimerThread.mainLoop(Timer.java:555)
  4. at java.util.TimerThread.run(Timer.java:505)

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

3.2、用ScheduledExecutorService替代Timer

      1、解决问题一:

  1. public class ScheduledExecutorTest {
  2. private  ScheduledExecutorService scheduExec;
  3. public long start;
  4. ScheduledExecutorTest(){
  5. this.scheduExec =  Executors.newScheduledThreadPool(2);
  6. this.start = System.currentTimeMillis();
  7. }
  8. public void timerOne(){
  9. scheduExec.schedule(new Runnable() {
  10. public void run() {
  11. System.out.println("timerOne,the time:" + (System.currentTimeMillis() - start));
  12. try {
  13. Thread.sleep(4000);
  14. } catch (InterruptedException e) {
  15. e.printStackTrace();
  16. }
  17. }
  18. },1000,TimeUnit.MILLISECONDS);
  19. }
  20. public void timerTwo(){
  21. scheduExec.schedule(new Runnable() {
  22. public void run() {
  23. System.out.println("timerTwo,the time:" + (System.currentTimeMillis() - start));
  24. }
  25. },2000,TimeUnit.MILLISECONDS);
  26. }
  27. public static void main(String[] args) {
  28. ScheduledExecutorTest test = new ScheduledExecutorTest();
  29. test.timerOne();
  30. test.timerTwo();
  31. }
  32. }

运行结果:

  1. timerOne,the time:1003
  2. timerTwo,the time:2005

      2、解决问题二

  1. public class ScheduledExecutorTest {
  2. private  ScheduledExecutorService scheduExec;
  3. public long start;
  4. ScheduledExecutorTest(){
  5. this.scheduExec =  Executors.newScheduledThreadPool(2);
  6. this.start = System.currentTimeMillis();
  7. }
  8. public void timerOne(){
  9. scheduExec.schedule(new Runnable() {
  10. public void run() {
  11. throw new RuntimeException();
  12. }
  13. },1000,TimeUnit.MILLISECONDS);
  14. }
  15. public void timerTwo(){
  16. scheduExec.scheduleAtFixedRate(new Runnable() {
  17. public void run() {
  18. System.out.println("timerTwo invoked .....");
  19. }
  20. },2000,500,TimeUnit.MILLISECONDS);
  21. }
  22. public static void main(String[] args) {
  23. ScheduledExecutorTest test = new ScheduledExecutorTest();
  24. test.timerOne();
  25. test.timerTwo();
  26. }
  27. }

运行结果:

    1. timerTwo invoked .....
    2. timerTwo invoked .....
    3. timerTwo invoked .....
    4. timerTwo invoked .....
    5. timerTwo invoked .....
    6. timerTwo invoked .....
    7. timerTwo invoked .....
    8. timerTwo invoked .....
    9. timerTwo invoked .....
    10. ........................

转自http://blog.csdn.net/chenssy/article/details/32703499

java定时任务Timer与ScheduledExecutorService<转>的更多相关文章

  1. Java定时任务Timer、TimerTask与ScheduledThreadPoolExecutor详解

     定时任务就是在指定时间执行程序,或周期性执行计划任务.Java中实现定时任务的方法有很多,本文从从JDK自带的一些方法来实现定时任务的需求. 一.Timer和TimerTask  Timer和Tim ...

  2. JAVA定时任务Timer

    故事起因 因业务需要,写了一个定时任务Timer,任务将在每天的凌晨2点执行,代码顺利码完,一切就绪,开始测试.运行程序,为了节省时间,将系统时间调整为第二天凌晨1点59分,看着秒针滴答滴答的转动,期 ...

  3. 详解java定时任务---Timer篇

    一.简介      在java的jdk中提供了Timer.TimerTask两个类来做定时任务. Timer是一种定时器工具,用来在一个后台线程计划执行指定任务,而TimerTask一个抽象类,它的子 ...

  4. java定时任务Timer/scheduleAtFixedRate

    Timer类是用来执行任务的类,定时器 scheduleAtFixedRate模式可以用,在这个模式下,Timer会尽量的让任务在一个固定的频率下运行. 参考:http://swiftlet.net/ ...

  5. Java 多线程之Timer与ScheduledExecutorService

    1.Timer管理延时任务的缺陷 a.以前在项目中也经常使用定时器,比如每隔一段时间清理项目中的一些垃圾文件,每个一段时间进行数据清洗:然而Timer是存在一些缺陷的,因为Timer在执行定时任务时只 ...

  6. Java定时任务的几种方法(Thread 和 Timer,线程池)

    /** * 普通thread * 这是最常见的,创建一个thread,然后让它在while循环里一直运行着, * 通过sleep方法来达到定时任务的效果.这样可以快速简单的实现,代码如下: * */ ...

  7. Java基础--定时任务Timer

    Java基础--定时任务Timer 一.Timer介绍 java.util.Timer java.util.TimerTask Timer是一个定时器类,通过该类可以为指定的定时任务进行配置.Time ...

  8. Java 中Timer和TimerTask 定时器和定时任务使用的例子

    转自:http://blog.csdn.net/kalision/article/details/7692796 这两个类使用起来非常方便,可以完成我们对定时器的绝大多数需求 Timer类是用来执行任 ...

  9. Java基础--定时任务Timer(转载)

    Java基础--定时任务Timer 一.Timer介绍 java.util.Timer java.util.TimerTask Timer是一个定时器类,通过该类可以为指定的定时任务进行配置.Time ...

随机推荐

  1. cxf使用wsdl文件生成代码

    1.先下载cxf包 http://cxf.apache.org/download.html,现在cxf包.(下载资源就有) 2.解压缩包,通过cmd命令进入到bin目录下(cd cxf\bin的路径) ...

  2. HDUOJ-Counting Triangles

    Counting Triangles Time Limit: 2000/1000 MS (Java/Others)    Memory Limit: 65536/32768 K (Java/Other ...

  3. INFO ipc.Client:Retrying connect to server 9000

    hadoop使用bin/start_all.sh命令之后,使用jps发现datanode无法启动 This problem comes when Datanode daemon on the syst ...

  4. invalid configuration x86_64-unknown-linux-gnu' machine x86_64-unknown' not recognized

    转载自:http://blog.csdn.net/php_boy/article/details/7382998 前两天在装机器软件的时候, 出现了下面的错误, invalid configurati ...

  5. JQueryMobile开发必须的知道的知识(转)

    移动Web页面的基本组成元素: 页面头部,页面内容,页面底部 <!DOCTYPE html> <html> <head> <title>My Page& ...

  6. PLSQL_统计信息系列08_统计信息生成和还原

    2015-02-01 Created By BaoXinjian

  7. js完美的div拖拽实例代码

    方案一: <!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3 ...

  8. Jquery定位插件,固定元素在页面某个位置,不随滚动条滚动

    代码: (function ($) { "use strict"; $.fn.pin = function (options) { var scrollY = 0, element ...

  9. Maker's Schedule, Manager's Schedule

    http://www.paulgraham.com/makersschedule.html manager's schedule 随意性强,指随时安排会面,开会等活动的 schedule; maker ...

  10. Codeforces 86C Genetic engineering (AC自己主动机+dp)

    题目大意: 要求构造一个串,使得这个串是由所给的串相连接构成,连接能够有重叠的部分. 思路分析: 首先用所给的串建立自己主动机,每一个单词节点记录当前节点可以达到的最长后缀. 開始的时候想的是dp[i ...