我们知道,Timer定时器是不支持时间范围内的执行,但是需求中有这样的情景,我们有一个预约扣款的需求,扣款成功后就会发短信,但是我们也不知道什么时候扣款成功,有时候半夜凌晨就会扣款成功,我们扣款成功判断这里用Timer定时器扫描的,每隔一段时间执行一次,但是半夜凌晨不希望扣款后发短信,以免打扰用户休息,要选择白天发短信,请看如下代码!
//从配置文件中读取时间.
public Map<String, Object> getTime(Properties properties){
Map<String, Object> map=new HashMap<String, Object>();
Integer hour= Integer.valueOf(properties.get("hour").toString()) ;
Integer min= Integer.valueOf(properties.get("min").toString()) ;
Integer second= Integer.valueOf(properties.get("second").toString()) ;
Integer frequency= Integer.valueOf(properties.get("frequency").toString()) ;
Calendar calendar = Calendar.getInstance();
calendar.set(Calendar.HOUR_OF_DAY, hour); // 控制时
calendar.set(Calendar.MINUTE, min); // 控制分
calendar.set(Calendar.SECOND, second); // 控制秒
Date time = calendar.getTime(); // 得出执行任务的时间,此处为今天的00:00:00
map.put("time", time);
map.put("frequency", 1000 * 60 * 60 *frequency);//1000 * 60 * 60 *frequency
return map;
}
/**
* 执行条件
* @param time 配置文件起始时间
* @param endHour 结束时间
* @return
*/
private boolean excCondition(Date time,int endHour){
boolean f=false;
SimpleDateFormat sdf=new SimpleDateFormat("HH");
String date=sdf.format(time);
Date c=new Date();
String curentString=sdf.format(c);
int curent=Integer.valueOf(curentString);
int start=Integer.valueOf(date);
int end =endHour;
if(curent>=start && curent<=end){
f= true;
}
return f;
}
//定时期执行
public void start(Properties properties) throws Exception {
final int endHour=Integer.valueOf(properties.getProperty("end"));
Map<String,Object> map=getTime(properties);
final Date time=(Date)map.get("time");
Integer frequency=(Integer) map.get("frequency");
Timer timer = new Timer();
timer.scheduleAtFixedRate(new TimerTask() {
public void run() {
// 处理方法
if(excCondition(time,endHour)){
logger.info("开始启动....");
//业务代码执行
BuyAction action = new BuyAction();
action.execute();
logger.info("执行完毕....");
}
}
}, time, frequency);
}