java配置自动任务,定期执行代码

时间:2022-02-13 06:02:25

任务调用类:

 package business.tools.service;

 import java.util.ArrayList;
import java.util.Calendar;
import java.util.Date;
import java.util.List; import org.apache.commons.logging.Log;
import org.apache.commons.logging.LogFactory;
import org.quartz.CronTrigger;
import org.quartz.Job;
import org.quartz.JobDetail;
import org.quartz.Scheduler;
import org.quartz.SchedulerException;
import org.quartz.SchedulerFactory;
import org.quartz.impl.StdSchedulerFactory; import business.tools.model.SalesDataMonitor;
import framework.corenew.DateFormatException;
import framework.corenew.MyString;
import framework.corenew.QDateTime;
import framework.corenew.UniversalManager; public class SalesDataMonitorManager extends UniversalManager{
private transient final static Log log = LogFactory.getLog(SalesDataMonitorManager.class);
private static SchedulerFactory sf ;
public static synchronized SchedulerFactory getSf() {
if(sf==null){
sf = new StdSchedulerFactory();
}
return sf;
} /**
* 保存销售数据范围时设定自动任务
* @param salesDataMonitor
* @throws Exception
*/
public void saveSalesMonitorJob(SalesDataMonitor salesDataMonitor) throws Exception{
if(salesDataMonitor==null){
return;
}
if("1".equals(salesDataMonitor.getType())){//如果type==1的不是监控范围数据
return;
} List<String> formartTimes = getFormatTime(salesDataMonitor);//对象中包含的任务时间
if(formartTimes==null||formartTimes.size()==0){
return;
} removeJobs(salesDataMonitor.getId(), "salesDataMonitorGroup");//删除任务 for(String formartTime:formartTimes){
String jobName = getJobName(salesDataMonitor, formartTime);
Job job = (Job)Class.forName("business.webservice.SalesDataMonitorJob").newInstance();
Scheduler sched = getSf().getScheduler();
JobDetail jobDetail = new JobDetail(jobName, "salesDataMonitorGroup", job.getClass());
jobDetail.getJobDataMap().put("salesDataMonitorId", salesDataMonitor.getId());
//触发器
CronTrigger trigger = new CronTrigger(jobName, "salesDataMonitorGroup");
trigger.setCronExpression(formartTime);//触发器时间设定
sched.scheduleJob(jobDetail,trigger);
//启动
if(!sched.isShutdown())
sched.start(); log.info("===============================任务添加成功!");
} } /**
* 拼出任务执行时间
* @param startTime
* @param endTime
* @param interval
* @return
* @throws DateFormatException
*/
private List<String> getFormatTime(SalesDataMonitor salesDataMonitor) throws Exception{
List<String> strList = new ArrayList<String>(); String catchDataType = salesDataMonitor.getCatchDataType();//抓取类型
if("1".equals(catchDataType)){
String weekDayStr = "";//周几的字符串
String weekDays = salesDataMonitor.getWeekDays();
if(MyString.isNoEmpty(weekDays)){
String[] weekDaysArr = weekDays.split("~");
for(int i=0;i<weekDaysArr.length;i++){
if(MyString.isNoEmpty(weekDaysArr[i])){
weekDayStr+=weekDaysArr[i];
if(i<weekDaysArr.length-1){
weekDayStr+=",";
}
} }
} String hoursAndMinutes = salesDataMonitor.getHoursAndMinutes();
if(MyString.isNoEmpty(hoursAndMinutes)){
String[] hoursAndMinutesArr = hoursAndMinutes.split("~");
for(int i=0;i<hoursAndMinutesArr.length;i++){
String[] hourAndMinuteArr = hoursAndMinutesArr[i].split(":");
String hourStr = hourAndMinuteArr[0];
String minuteStr = hourAndMinuteArr[1]; StringBuffer formartTime = new StringBuffer();
formartTime.append("0 ");
formartTime.append(minuteStr+" ");
formartTime.append(hourStr+" ? * ");
formartTime.append(weekDayStr);//周的表示 用MON-SUN或者1-7,不过注意:数字1是周日,2是周一,依次向下推 strList.add(formartTime.toString()); }
}
}else if("2".equals(catchDataType)){
try{
String fixedTimes = salesDataMonitor.getFixedTimes();
if(MyString.isNoEmpty(fixedTimes)){
String[] fixedTimesArr = fixedTimes.split("~");
for(int i=0;i<fixedTimesArr.length;i++){
Date fixedTime = QDateTime.stringToDate(fixedTimesArr[i], "yyyy-MM-dd HH:mi");
int compared = compareTimeToNow(fixedTime);
if(compared==1){
throw new Exception("您填写的时间已过期,请核对!");
}
String yearStr = QDateTime.dateToString(fixedTime, "yyyy");
String monthStr = QDateTime.dateToString(fixedTime, "MM");
String dateStr = QDateTime.dateToString(fixedTime, "dd"); String hourStr = QDateTime.dateToString(fixedTime, "HH");
String minStr = QDateTime.dateToString(fixedTime, "mi"); StringBuffer formartTime = new StringBuffer();
formartTime.append("0 ") ;
formartTime.append(minStr+" ");
formartTime.append(hourStr+" ");
formartTime.append(dateStr+" ");
formartTime.append(monthStr+" ? ");
formartTime.append(yearStr); strList.add(formartTime.toString()); }
}
}catch(Exception e){
e.printStackTrace();
}
} log.info("自动任务触发时间:======"+strList.toString());
return strList;
}
/**
* 一个日期和当前时间比较
* @param time
* @return
* @throws DateFormatException
*/
private int compareTimeToNow(Date time) throws DateFormatException{ Calendar inTime = Calendar.getInstance();
inTime.setTime(time); Calendar nowTime = Calendar.getInstance();
String currentTimeStr = QDateTime.dateToString(new Date(), "yyyy-MM-dd HH:mi");
Date currentTime = QDateTime.stringToDate(currentTimeStr, "yyyy-MM-dd HH:mi");
nowTime.setTime(currentTime); int compared = nowTime.compareTo(inTime);
return compared;
} private String getJobName(SalesDataMonitor salesDataMonitor,String formartTime) throws Exception{
//拼出任务名字
StringBuffer jobName = new StringBuffer();
jobName.append(salesDataMonitor.getId());//id
jobName.append("φ");
jobName.append(salesDataMonitor.getBusinessType());//国际国内
jobName.append("φ");
jobName.append(salesDataMonitor.getCarrierCode());//航空公司
jobName.append("φ");
jobName.append(salesDataMonitor.getClasses());//舱位
jobName.append("φ");
jobName.append(salesDataMonitor.getDepArea()+"-"+salesDataMonitor.getArrArea());//区域
jobName.append("φ");
jobName.append(salesDataMonitor.getIsArrival());//是限定还是排除
jobName.append("φ");
jobName.append(salesDataMonitor.getDeparture()+"-"+salesDataMonitor.getArrival());//限定和排除的机场三字码
jobName.append("φ");
jobName.append(salesDataMonitor.getTourDateBegins()+"-"+salesDataMonitor.getTourDateEnds());//旅行时间
jobName.append("φ");
jobName.append(salesDataMonitor.getEtdzBegins()+"-"+salesDataMonitor.getEtdzEnds());//出票时间
jobName.append("φ");
jobName.append(salesDataMonitor.getCatchDataType());//抓取类型
jobName.append("φ");
jobName.append(formartTime);//任务时间 return jobName.toString();
} public void removeJobs(String objectId,String groupName) throws SchedulerException{
if(!MyString.isNoEmpty(objectId)){
return;
}
Scheduler sched = getSf().getScheduler();
String[] jobNames = sched.getJobNames(groupName);
if(jobNames==null||jobNames.length==0){
return;
}
for(String jobName :jobNames){
if(jobName.startsWith(objectId)){
removeJob(jobName);//清除任务
}
} }
/**
* 删除任务
* @param jobName
* @throws SchedulerException
*/
public static void removeJob(String jobName)
throws SchedulerException{
Scheduler sched = getSf().getScheduler();
sched.pauseTrigger(jobName,"salesDataMonitorGroup");//停止触发器
sched.unscheduleJob(jobName,"salesDataMonitorGroup");//移除触发器
sched.deleteJob(jobName,"salesDataMonitorGroup");//删除任务
log.info("删除任务成功!");
}
}

任务类:Job

 package business.webservice;

 import java.util.Date;

 import org.apache.commons.logging.Log;
import org.apache.commons.logging.LogFactory;
import org.quartz.Job;
import org.quartz.JobExecutionContext;
import org.quartz.JobExecutionException; import business.tools.service.BookinfoManager;
import framework.corenew.QDateTime;
import framework.corenew.SpringUtil; public class SalesDataMonitorJob implements Job{
private transient final Log log = LogFactory.getLog(SalesDataMonitorJob.class); public void execute(JobExecutionContext jobEC) throws JobExecutionException {
String currentTime = QDateTime.dateToString(new Date(), "yyyy-MM-dd HH:mi:ss");
log.info("===================调用SalesDataMonitorJob时间 :"+currentTime+"====================="); String salesDataMonitorId = (String)jobEC.getJobDetail().getJobDataMap().get("salesDataMonitorId"); try {
BookinfoManager bookinfoManager = (BookinfoManager) SpringUtil.getBean("bookinfoManager");
bookinfoManager.saveGroupBookInfoBySalesDataMonitor(salesDataMonitorId);
} catch (Exception e) {
e.printStackTrace();
} } }

时间的格式拼法详见下章