我們知道,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);
}