定时任务Timer使用

1、任务基类:

package com.sxit.common;

import java.util.Date;
import java.util.TimerTask;

/**
 * @功能:任务基类
 * @作者: smile
 * @时间:2013-3-28 下午2:32:29
 * @版本:1.0
 */
public class BaseTimerTask extends TimerTask{

	//任务类型
	public int type;
	
	//执行周期时间  毫秒
	public long period;
	
	//指定延迟执行时间 
	public long delay;
	
	//指定运行时间
	public Date runTime;
	
	/**
	 * 指定的时间运行,仅运行一次
	 * 对应Timer中的 schedule(TimerTask task, Date time)
	 */
	public static final int Schedule_Date=1;
	
	/**
	 * 指定时间开始周期运行(基于延迟)
	 * 用固定延迟调度。使用本方法时,在任务执行中的每一个延迟会传播到后续的任务的执行。
	 * 对应Timer中的schedule(TimerTask task, Date firstTime, long period)
	 */
	public static final int Schedule_Date_Period=2;
	
	/**
	 * 指定时间开始周期运行(基于固定比率)
	 * 用固定比率调度。使用本方法时,所有后续执行根据初始执行的时间进行调度,从而希望减小延迟
	 * 如果由于任何原因(如业务逻辑复杂、垃圾回收或其他后台活动)而延迟了某次执行,则将快速连续地出现两次或更多次执行,从而使后续执行能够赶上来
	 * 对应Tiemr中的scheduleAtFixedRate(TimerTask task, Date firstTime, long period) 
	 */
	public static final int FixedRate_Date=3;
	
	/**
	 * 指定延迟开始运行(基于固定比率)
	 * 用固定比率调度。使用本方法时,所有后续执行根据初始执行的时间进行调度,从而希望减小延迟
	 * 如果由于任何原因(如业务逻辑复杂、垃圾回收或其他后台活动)而延迟了某次执行,则将快速连续地出现两次或更多次执行,从而使后续执行能够赶上来
	 * 对应Timer中的scheduleAtFixedRate(TimerTask task, long delay, long period)
	 */
	public static final int FixedRate_Period=4;
	
	public BaseTimerTask(int type){
		this.type = type;
	}
	
	public void run() {}
	
}

 2、定时器类:

package com.sxit.common;

import java.util.HashMap;
import java.util.Iterator;
import java.util.Map;
import java.util.Timer;

/**
 * @功能:定时器基类
 * @作者: smile
 * @时间:2013-3-28 下午3:39:15
 * @版本:1.0
 */
public class BaseTimer extends Timer {

	// Timer队列
	private static Map<String, BaseTimerTask> timerMap = new HashMap<String, BaseTimerTask>();

	private static BaseTimer timer = new BaseTimer();

	private BaseTimer() {
	}

	public static BaseTimer getInstance() {
		return timer;
	}

	// 向队列中添加Timer
	public void addTimer(String timerName, BaseTimerTask task) {
		timerMap.put(timerName, task);
	}

	// 启动Timer
	public synchronized void startTask() {
		if (timerMap != null) {
			Iterator<String> itr = timerMap.keySet().iterator();
			while (itr.hasNext()) {
				Object obj = itr.next();
				BaseTimerTask task = timerMap.get(obj.toString());
				if (task.type == BaseTimerTask.Schedule_Date) {
					this.schedule(task, task.runTime);
				} else if (task.type == BaseTimerTask.Schedule_Date_Period) {
					this.schedule(task, task.runTime, task.period);
				} else if (task.type == BaseTimerTask.FixedRate_Date) {
					this.scheduleAtFixedRate(task, task.runTime, task.period);
				} else if (task.type == BaseTimerTask.FixedRate_Period) {
					this.scheduleAtFixedRate(task, task.delay, task.period);
				} else {
					// 配置信息不正确 退出
					System.exit(0);
				}
			}
		}
	}

	// 销毁Timer
	public synchronized void stopTask() {
		if (timerMap != null) {
			Iterator<String> itr = timerMap.keySet().iterator();
			while (itr.hasNext()) {
				Object obj = itr.next();
				BaseTimerTask task = timerMap.get(obj.toString());
				if(task != null){
					task.cancel();
				}
			}
		}
	}

}

 3、容器启动时加载Timer配置文件

package com.sxit.common;

import java.io.File;
import java.io.FileInputStream;
import java.io.FileNotFoundException;
import java.io.IOException;
import java.io.InputStream;
import java.net.URL;
import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.util.Date;
import java.util.Iterator;
import java.util.Properties;

/**
 * @功能:Web容器启动 装载Timer信息
 * @作者: smile
 * @时间:2013-3-28 下午3:50:25
 * @版本:1.0
 */
public class TimerConfig {

	private static TimerConfig timerConfig = new TimerConfig();
	// Timer配置文件名
	private static String fileName = "mainTimer.properties";

	private static Properties config = new Properties();

	private TimerConfig() {
		init();
	}

	public static TimerConfig getInstance() {
		return timerConfig;
	}

	// 加载配置Timer配置文件
	public void init() {

		InputStream is = null;
		try {
			URL url = Thread.currentThread().getContextClassLoader().getResource("");
			File f = new File(url.getPath() + File.separator + fileName);
			is = new FileInputStream(f);
			config.clear();
			config.load(is);
		} catch (FileNotFoundException e) {
			e.printStackTrace();
		} catch (IOException e) {
			e.printStackTrace();
		} finally {
			if (is != null) {
				try {
					is.close();
				} catch (IOException e) {
					e.printStackTrace();
				}
			}
		}
	}

	// 向队列中添加Timer
	public void setTask() {

		try {
			if (config != null && config.size() > 0) {

				BaseTimer timer = BaseTimer.getInstance();
				Iterator itr = config.keySet().iterator();
				while (itr.hasNext()) {
					Object obj = itr.next();
					// 配置文件格式
					// Timer名 = Timer类路径,Timer类型,执行时间,执行周期,延迟时间
					String[] tmp = config.get(obj).toString().split(",");
					int type = Integer.parseInt(tmp[1]);
					// 通过反射生成指定Timer类的对象 并给type赋值
					BaseTimerTask task = (BaseTimerTask) Class.forName(tmp[0]).getConstructor(new Class[] { Integer.TYPE }).newInstance(new Object[] { type });
					if (type == BaseTimerTask.Schedule_Date) {
						task.runTime = parseTime(tmp[2]);
					} else if (type == BaseTimerTask.Schedule_Date_Period) {
						task.runTime = parseTime(tmp[2]);
						task.period = Long.parseLong(tmp[3]);
					} else if (type == BaseTimerTask.FixedRate_Date) {
						task.runTime = parseTime(tmp[2]);
						task.period = Long.parseLong(tmp[3]);
					} else if (type == BaseTimerTask.FixedRate_Period) {
						task.runTime = parseTime(tmp[2]);
						task.delay = Long.parseLong(tmp[4]);
					} else {
						System.exit(0);// 配置文件出错
					}
					timer.addTimer(obj.toString(), task);// 添加Timer到队列中
				}
			}
		} catch (Exception e) {
			e.printStackTrace();
		}
	}

	//字符串转换Date
	public Date parseTime(String s) throws ParseException {
		SimpleDateFormat format = new SimpleDateFormat("HH:mm:ss");
		return format.parse(s);
	}

}

 4、监听器:

package com.sxit.util;

import javax.servlet.ServletContextEvent;
import javax.servlet.ServletContextListener;

import com.sxit.common.BaseTimer;
import com.sxit.common.TimerConfig;

public class ContextListener implements ServletContextListener {
	
	/**
	 * Web容器初始化
	 */
	public void contextInitialized(ServletContextEvent sce) {
		
		BaseTimer.getInstance().stopTask();
	}
	
	/**
	 * Web容器销毁
	 */
	public void contextDestroyed(ServletContextEvent sce) {
		
		//读取Timer配置文件 并加入到队列中
		TimerConfig.getInstance().setTask();
		
		//启动Timer
		BaseTimer.getInstance().startTask();
	}
}

 5、测试Timer:

package com.sxit.timertask;

import com.sxit.common.BaseTimerTask;

public class TestTask extends BaseTimerTask {
	
	public TestTask(int type) {
		super(type);
	}
	
	public void run() {
		System.out.println("这里执行任务");
	}
	
}

 6、Timer配置文件:

#增值业务用户导入
#ImportCpUserTimerTask=ImportCpUserTimerTask,timertask.imports.ImportCpUserTimerTask,2,1000,5000

#未定制用户导入
#ImportUnOrderUserTimerTask=ImportUnOrderUserTimerTask,timertask.imports.ImportUnOrderUserTimerTask,2,1000,5000

#增值业务日报表
#CpUserDayTimerTask=CpUserDayTimerTask,timertask.businessRpt.CpUserDayTimerTask,5,05:33:00,86400000

#亲情号码按班级导入
#ImportFamilyMobileTaskNew=ImportManage,timertask.imports.familymobile.ImportFamilyMobileTaskNew,2,1000,50000

#定时解析10086的投诉文档
#UsercomplaintTimerTask=UsercomplaintTimerTask,timertask.businessRpt.UsercomplaintTimerTask,1,09:45:00,86400000

#定时解析10086的投诉文档(new)
#UserComplaintTimerTaskNew=UserComplaintTimerTaskNew,timertask.businessRpt.UserComplaintTimerTaskNew,1,03:00:00,86400000

#异网用户导入
ImportYwUserTimerTask=ImportYwUserTimerTask,timertask.imports.ImportYwUserTimerTask,2,1000,5000

猜你喜欢

转载自luan.iteye.com/blog/1838132
今日推荐