---
title: "Timer与ScheduledExecutorService 的使用和区别"
author: "xbgd"
date: "2013-06-21T21:47:43Z"
tags: []
categories: ["编程语言"]
slug: "timer-scheduledexecutorservice"
draft: false
lastmod: "2013-06-21T21:47:43Z"
id: 1892307
url: "https://xbgd.iteye.com/blog/1892307"
---

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 plain](http://blog.csdn.net/qq522935502/article/details/8166284 "view plain")[copy](http://blog.csdn.net/qq522935502/article/details/8166284 "copy")[print](http://blog.csdn.net/qq522935502/article/details/8166284 "print")[?](http://blog.csdn.net/qq522935502/article/details/8166284 "?")

01. public class TimerTest {
02. private static final Timer timer1 = new Timer(true);
03. public static void main(String\[] args) {
04. timer1.schedule(new TimerTask(){
05. @Override
06. public void run() {
07. System.out.println("执行定时任务...");
08. }
09. }, 0, 60000\*1);
10. }
11. }

 

ScheduledExecutorService:

**\[java]** [view plain](http://blog.csdn.net/qq522935502/article/details/8166284 "view plain")[copy](http://blog.csdn.net/qq522935502/article/details/8166284 "copy")[print](http://blog.csdn.net/qq522935502/article/details/8166284 "print")[?](http://blog.csdn.net/qq522935502/article/details/8166284 "?")

01. public class ScheduleExecutor {
02. private final ScheduledExecutorService scheduler =
03. Executors.newScheduledThreadPool(1);
04. public void beepForMin() {
05. final ScheduledFuture&lt;?&gt; beeperHandle = scheduler.scheduleAtFixedRate(
06. new Runnable() {
07. public void run() {
08. System.out.println("执行。。。");
09. }
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. }