`

Timer与ScheduledExecutorService 的使用和区别

阅读更多

Timer和ScheduledExecutorService都可以用来做定时任务,有管理任务延迟执行("如1000ms后执行任务")以及周期性执行("如每500ms执行一次该任务")。但至从JDK1.5之后,建议采用ScheduledExecutorService。

原因如下:

1、Timer对调度的支持是基于绝对时间,而不是相对时间的,由此任务对系统时钟的改变是敏感的;但ScheduledThreadExecutor只支持相对时间。

2、如果TimerTask抛出未检查的异常,Timer将会产生无法预料的行为。Timer线程并不捕获异常,所以 TimerTask抛出的未检查的异常会终止timer线程。此时,已经被安排但尚未执行的TimerTask永远不会再执行了,新的任务也不能被调度了。

3、Timer里面的任务如果执行时间太长,会独占Timer对象,使得后面的任务无法几时的执行 ,ScheduledExecutorService不会出现Timer的问题(除非你只搞一个单线程池的任务区)

 

Timer:

  1. public class TimerTest {  
  2.     private static final Timer timer1 = new Timer(true);   
  3.       
  4.     public static void main(String[] args) {  
  5.         timer1.schedule(new TimerTask(){  
  6.             @Override  
  7.             public void run() {  
  8.                 System.out.println("执行定时任务...");  
  9.             }  
  10.         }, 060000*1);  
  11.     }  
  12. }  

 

ScheduledExecutorService:

  1. public class ScheduleExecutor {  
  2.    private final ScheduledExecutorService scheduler =   
  3.       Executors.newScheduledThreadPool(1);  
  4.   
  5.    public void beepForMin() {  
  6.         final ScheduledFuture<?> beeperHandle = scheduler.scheduleAtFixedRate(  
  7.                 new Runnable() {  
  8.                     public void run() {  
  9.                         System.out.println("执行。。。");  
  10.                     }  
  11.                 }, 010, SECONDS);  
  12.           
  13.         scheduler.schedule(new Runnable() {  
  14.             public void run() {  
  15.                 beeperHandle.cancel(true);  
  16.                 System.exit(0);  
  17.             }  
  18.         }, 30, SECONDS);  
  19.     }  
  20.      
  21.      
  22.    public static void main(String[] args) {  
  23.        ScheduleExecutor se = new ScheduleExecutor();  
  24.        se.beepForMin();  
  25.    }  
  26. }  
分享到:
评论

相关推荐

Global site tag (gtag.js) - Google Analytics