JAVA Timer 的使用例子

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

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,有空可以做个例子看看。

上一篇: 发现一个在线面试程序员的网站 collabedit.com
下一篇: 发布一个Django开发的公司网站源码,可以作为Django 例子学习
 评论 ( What Do You Think )
名称
邮箱
网址
评论
验证
   
 

 


  • 微信公众号

  • 我的微信

站点声明:

1、一号门博客CMS,由Python, MySQL, Nginx, Wsgi 强力驱动

2、部分文章或者资源来源于互联网, 有时候很难判断是否侵权, 若有侵权, 请联系邮箱:summer@yihaomen.com, 同时欢迎大家注册用户,主动发布无版权争议的 文章/资源.

3、鄂ICP备14001754号-3, 鄂公网安备 42280202422812号