ITeye博客

Timer与ScheduledExecutorService 的使用和区别

xbgd · 2013-06-21 21:47 · JAVA源码 · 编程语言 · Markdown

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

原因如下:

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

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

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

 

Timer:

[java] view plaincopyprint?

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

 

ScheduledExecutorService:

[java] view plaincopyprint?

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

评论(0)

暂无评论。

评论功能维护中,当前仅展示历史评论。