今日看了《
Java Concurrency in Practice》的第6.2.5章节,才知道java.util.Timer真是问题多多啊。
Timer任务执行过程中,如果下一次计时到了,会产生任务冲突问题。这在多线程的环境下会更加突出。
另外如果Timer任务执行过程中发生异常,Timer仍然会继续工作!
jdk5的java.util.concurrent.ScheduledExecutorService很好的解决了以上问题:
1 import java.util.concurrent.Executors;
2 import java.util.concurrent.ScheduledExecutorService;
3 import java.util.concurrent.ScheduledFuture;
4 import static java.util.concurrent.TimeUnit.*;
5
6 public class BeeperControl {
7
8 private final ScheduledExecutorService scheduler = Executors.newScheduledThreadPool(1);
9 private int count = 0;
10
11 public void beepForAnHour() {
12 final Runnable beeper = new Runnable() {
13
14 public void run() {
15 if (count == 5) {
16 int i = 1 / 0;
17 }
18 System.out.println(count++);
19 }
20 };
21 final ScheduledFuture<?> beeperHandle = scheduler.scheduleAtFixedRate(beeper, 5, 1, SECONDS);
22 scheduler.schedule(new Runnable() {
23
24 public void run() {
25 System.out.println("cancel!");
26 beeperHandle.cancel(true);
27 scheduler.shutdown();
28 }
29 }, 15, SECONDS);
30 }
31 }
PS:
Spring和EJB都有自己的定时任务功能,也是比较好的选择。