java中Timer的使用

来源:互联网 发布:淘宝网电视机顶盒架 编辑:程序博客网 时间:2024/06/04 19:30

在应用开发中,经常需要一些周期性的操作,比如每5分钟检查一下新邮件等。对于这样的操作最方便、高效的实现方式就是使用java.util.Timer工具类。比如下面的代码每5分钟检查一遍是否有新邮件:

1.        private java.util.Timer timer;

2.        timer = new Timer(true);

3.        timer.schedule(new java.util.TimerTask() {

4.        public void run() {

5.        //server.checkNewMail(); 检查新邮件

6.        }

7.        }, 0, 5*60*1000);


使用这几行代码之后,Timer本身会每隔5分钟调用一遍server.checkNewMail()方法,不需要自己启动线程。Timer本身也是多线程同步的,多个线程可以共用一个Timer,不需要外部的同步代码。
    
在《The Java Tutorial》中有更完整的例子:

1.        public class AnnoyingBeep {

2.        Toolkit toolkit;

3.        Timer timer;

4.         

5.        public AnnoyingBeep() {

6.        toolkit = Toolkit.getDefaultToolkit();

7.        timer = new Timer();

8.        timer.schedule(new RemindTask(),

9.        0,        //initial delay

10.     1*1000);  //subsequent rate

11.     }

12.      

13.     class RemindTask extends TimerTask {

14.     int numWarningBeeps = 3;

15.      

16.     public void run() {

17.     if (numWarningBeeps > 0) {

18.     toolkit.beep();

19.     System.out.println("Beep!");

20.     numWarningBeeps--;

21.     } else {

22.     toolkit.beep();

23.     System.out.println("Time's up!");

24.     //timer.cancel(); //Not necessary because we call System.exit

25.     System.exit(0);   //Stops the AWT thread (and everything else)

26.     }

27.     }

28.     }

29.     ...

30.     }

这段程序,每隔3秒响铃一声,并打印出一行消息。循环3次。程序输出如下:
Task scheduled.
Beep!      
Beep!      //one second after the first beep
Beep!      //one second after the second beep
Time's up! //one second after the third beep

Timer
类也可以方便地用来作为延迟执行,比如下面的代码延迟指定的时间(以秒为单位)执行某操作。类似电视的延迟关机功能。

1.        ...

2.        public class ReminderBeep {

3.        ...

4.        public ReminderBeep(int seconds) {

5.        toolkit = Toolkit.getDefaultToolkit();

6.        timer = new Timer();

7.        timer.schedule(new RemindTask(), seconds*1000);

8.        }

9.         

10.     class RemindTask extends TimerTask {

11.     public void run() {

12.     System.out.println("Time's up!");

13.     toolkit.beep();

14.     //timer.cancel(); //Not necessary because we call System.exit

15.     System.exit(0);   //Stops the AWT thread (and everything else)

16.     }

17.     }

18.     ...

19.     } 

原创粉丝点击