JAVA Timer 的使用例子

Java 的 java.util 中有 Timer 这个类,在处理一些定时执行的程序或者重复多次执行的程序时就比较有用。而在这里面有几个比较重要的类:
1. Task Queue
在内部,Timer 使用 TaskQueues 来维护要处理的任务。这些任务会被 TimerThread  顺序的执行.
2. Timer Thread
Timer Thread 会监视 Task Queues 的任务,并顺序的处理它,但是一个 Timer 只有一个 TimerThread  的实例,因此,只能一个一个的处理,当在处理其中一个任务的时候,其他的就必须等待.
3. TimerTask
这是最常用的了,这是一个抽象类它实现了多线程的 Runable 接口,所以作为程序员在使用的时候,最主要的就是实现的 run 方法.

下面是一个具体使用的例子,做了一个类似心跳机制的东西,隔一段时间发送一次心跳,在一分钟后结束.
程序代码 程序代码

package com.yihaomen.heartbeat;

import java.util.Calendar;
import java.util.Timer;
import java.util.TimerTask;

public class TimerExample {
    private String healthStatus = "GREEN";

    public static void main(String[] args) {

        TimerExample example = new TimerExample();
        example.setHealthStatus("GREEN");

        // Create the Timer object
        Timer timer = new Timer("Timer Example");
        // Create Timer task created to send heartBeats
        TimerTask taskToExecute = new TimerTaskSendHeartBeat(example);
        //1秒之后执行,没个10秒执行一次
        timer.scheduleAtFixedRate(taskToExecute, 1000, 10000);

        // Create Timer task to setHeartBeatStatus
        TimerTask setHeartBeatStatus = new TimerTaskUpdateHeartBeat(example);
        // 在30秒之后执行第一次.
        timer.schedule(setHeartBeatStatus, 30000);
        // 等待60秒,清楚定时器
        try {
            Thread.sleep(60000);
        } catch (InterruptedException e) {
        }
        System.out.println("Cancelling Timer Cleanly after 60 seconds");
        timer.cancel();
    }

    
    public String getHealthStatus() {
        return this.healthStatus;
    }


    public void setHealthStatus(String healthStatus) {
        this.healthStatus = healthStatus;
    }
}

class TimerTaskUpdateHeartBeat extends TimerTask {

    TimerExample healthClass = null;

    public TimerTaskUpdateHeartBeat(TimerExample healthClass) {
        this.healthClass = healthClass;
    }

    @Override
    public void run() {
        System.out.println("Task 2:: 30 seconds completed :: Updating health "
                + "status to AMBER");
        healthClass.setHealthStatus("AMBER");
    }

}

class TimerTaskSendHeartBeat extends TimerTask {

    TimerExample healthStatusHolder = null;

    public TimerTaskSendHeartBeat(TimerExample healthStatusHolder) {
        this.healthStatusHolder = healthStatusHolder;
    }

    HeartBeatMessage message = null;

    @Override
    public void run() {

        // create HeartBeat message by getting Health Status (RED/GREEN/AMBER)
        // Error Code, if any AND time at which heartbeat is sent to help
        // receiver discard any delayed messages due to latency
        message = new HeartBeatMessage(
                this.healthStatusHolder.getHealthStatus(), Calendar
                        .getInstance().getTimeInMillis(), -1);

        System.out.println("Sending HeartBeat Message");

        // Send the message to Monitoring Dashboard
        System.out.println(message);

        System.out.println("HeartBeat Message Sent");
    }

    /**
     * Simple POJO which is a heartbeat message object It can have any decoder
     * encoder mechanism to send over any messaging platform
     */
    class HeartBeatMessage {
        private String status;
        private long heartBeatTime;
        private int errorCode;

        public HeartBeatMessage(String status, long heartBeatTime, int errorCode) {
            this.status = status;
            this.heartBeatTime = heartBeatTime;
            this.errorCode = errorCode;
        }

        public String getStatus() {
            return status;
        }

        public long getHeartBeatTime() {
            return heartBeatTime;
        }

        public int getErrorCode() {
            return errorCode;
        }

        @Override
        public String toString() {
            return "status: " + status + " timeOfHeartBeat: "
                    + new java.util.Date(this.heartBeatTime) + " errCode : "
                    + this.errorCode;
        }
    }
}


产生的结果如下:
程序代码 程序代码

Sending HeartBeat Message
status: GREEN timeOfHeartBeat: Tue Jun 24 20:47:37 CST 2014 errCode : -1
HeartBeat Message Sent
Sending HeartBeat Message
status: GREEN timeOfHeartBeat: Tue Jun 24 20:47:47 CST 2014 errCode : -1
HeartBeat Message Sent
Sending HeartBeat Message
status: GREEN timeOfHeartBeat: Tue Jun 24 20:47:57 CST 2014 errCode : -1
HeartBeat Message Sent
Task 2:: 30 seconds completed :: Updating health status to AMBER
Sending HeartBeat Message
status: AMBER timeOfHeartBeat: Tue Jun 24 20:48:07 CST 2014 errCode : -1
HeartBeat Message Sent
Sending HeartBeat Message
status: AMBER timeOfHeartBeat: Tue Jun 24 20:48:17 CST 2014 errCode : -1
HeartBeat Message Sent
Sending HeartBeat Message
status: AMBER timeOfHeartBeat: Tue Jun 24 20:48:27 CST 2014 errCode : -1
HeartBeat Message Sent
Cancelling Timer Cleanly after 60 seconds


可以根据程序里面设定的时间段分析下结果.

另外,Timer 是线程安全的。而且一旦 Timer 销毁,相关的thread 也会销毁,因为 Timer 创建了宿主线程。

其实如果是在jdk 1.5 以上的版本,如果想用 定时执行某个任务一次或多次,有一个更好的东西:ScheduledThreadPoolExecutor,有空可以做个例子看看。


除非申明,文章均为一号门原创,转载请注明本文地址,谢谢!
文章来自: 本站原创
引用通告: 查看所有引用 | 我要引用此文章
Tags: timer
相关日志:
评论: 0 | 引用: 0 | 查看次数: -
发表评论
昵 称:
密 码: 游客发言不需要密码.
内 容:
验证码: 验证码
选 项:
虽然发表评论不用注册,但是为了保护您的发言权,建议您注册帐号.