JAVA 定时器框架

时间:2021-08-29 02:27:20

web.xml

<display-name>XXX Web Application</display-name>
<context-param>
<param-name>contextConfigLocation</param-name>
<param-value>
/WEB-INF/conf/frame-spring.xml
</param-value>
</context-param>
<listener>
<listener-class>
org.springframework.web.context.ContextLoaderListener
</listener-class>
</listener>
<context-param>
<param-name>configLoader</param-name>
<param-value>
/WEB-INF/conf/frame-spring.xml
</param-value>
</context-param>
<listener>
<listener-class>
org.springframework.web.context.request.RequestContextListener
</listener-class>
</listener>

frame-spring.xml

<import resource="applicationContext-quartz.xml" />

applicationContext-quartz.xml

<?xml version="1.0" encoding="UTF-8"?>
<beans xmlns="http://www.springframework.org/schema/beans"
xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xsi:schemaLocation="http://www.springframework.org/schema/beans http://www.springframework.org/schema/beans/spring-beans-3.2.xsd">


<!--动态定时任务工厂-->
<bean id="schedulerFactoryBean" class="org.springframework.scheduling.quartz.SchedulerFactoryBean" scope="singleton" >
</bean>

<!--Tomcat启动之后加载定时(启用)任务运行-->
<bean id="quartzInitListener" class="com.xxx.quartz.QuartzInitListener" scope="singleton" />

</beans>

QuartzInitListener.java

import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.context.ApplicationListener;
import org.springframework.context.event.ContextRefreshedEvent;

/**
* 任务加载类
* Tomcat启动之后自动调用处于 运行中 的任务
*/

public class QuartzInitListener implements ApplicationListener<ContextRefreshedEvent> {
protected static final Logger LOGGER = LoggerFactory.getLogger(QuartzInitListener.class);
@SuppressWarnings("unchecked")
@Override
public void onApplicationEvent(ContextRefreshedEvent ev) {
if("0".equals(DataProcessAtom.autoTaskSwitch)){
//关闭了定时任务,不加载任务
}else{
//防止重复执行。
if(ev.getApplicationContext().getParent() == null){
DataExchangeAssembly dataExchange = new TaskInQurartz().getDataExchage();
ReflectionUtil.reflectThrowExceptionClearly("SXXXXXX",dataExchange,null);
}
}
}
}

SXXXXXX

    /**
* 初始化运行中的任务
* @param dataExchange
* @return
*/

public GenericResult initScheduleJob2acctDataProcess(DataExchangeAssembly dataExchange){
try {
try {
//获取运行中的任务
List<ScheduleJob> jobList = getDoingJobs(dataExchange);
for (ScheduleJob job : jobList) {
TriggerKey triggerKey = TriggerKey.triggerKey(job.getJobName(), job.getJobGroup());
//获取trigger,即在spring配置文件中定义的 bean id="myTrigger"
CronTrigger trigger = (CronTrigger) scheduler.getTrigger(triggerKey);
//不存在,创建一个
if (null == trigger) {
JobDetail jobDetail = JobBuilder.newJob(QuartzJobFactory.class)
.withIdentity(job.getJobName(), job.getJobGroup()).build();
jobDetail.getJobDataMap().put("scheduleJob", job);
//表达式调度构建器
CronScheduleBuilder scheduleBuilder = CronScheduleBuilder.cronSchedule(job
.getCronExpression());
//按新的cronExpression表达式构建一个新的trigger
trigger = TriggerBuilder.newTrigger().withIdentity(job.getJobName(), job.getJobGroup()).withSchedule(scheduleBuilder).build();
scheduler.scheduleJob(jobDetail, trigger);
} else {
// Trigger已存在,那么更新相应的定时设置
//表达式调度构建器
CronScheduleBuilder scheduleBuilder = CronScheduleBuilder.cronSchedule(job
.getCronExpression());
//按新的cronExpression表达式重新构建trigger
trigger = trigger.getTriggerBuilder().withIdentity(triggerKey)
.withSchedule(scheduleBuilder).build();
//按新的trigger重新设置job执行
scheduler.rescheduleJob(triggerKey, trigger);
}
}
//提示码:0;提示信息:DIA_加载运行中的任务成功
return new AtomResult(BusinessPrompt.ATOM_SUC_CODE, BusinessPrompt.START_SCHEDULE_JOB_SUC_MSG, null);
}catch (Exception e){
//提示码:-100326;提示信息:DIA_开启任务失败
throw new AtomException(BusinessPrompt.START_SCHEDULE_JOB_FAIL_CODE, BusinessPrompt.START_SCHEDULE_JOB_FAIL_MSG+",详细异常:【"+e.getMessage()+"】", FrameworkConstants.ATOM_LVL);
}
}catch (AtomException exception) {
return new AtomResult(exception.getErrorCode(), exception.getMessage());
}
}

private List<ScheduleJob> getDoingJobs(DataExchangeAssembly dataExchange) {
Map<String, String> params = (Map<String, String>) dataExchange.getBusinessData("params");
Map pm = new HashMap();
pm.put("JOB_STATUS","1");
dataExchange.setBusinessData("params",pm);
List<ScheduleJob> ls = getJob(dataExchange);
dataExchange.setBusinessData("params",params);
return ls;
}
public List<ScheduleJob> getJob(DataExchangeAssembly dataExchange) {
//根据任务标识获取任务(从数据库中拿)
List<Map> jobMaps = queryScheduleJob2acctDataProcess(dataExchange).getDataList();
List<ScheduleJob> list = new ArrayList<ScheduleJob>();
for (int i = 0,len=jobMaps.size(); i < len; i++) {
ScheduleJob job = new ScheduleJob();
Map jobMap = jobMaps.get(i);
String execNo = ObjectUtils.toString(jobMap.get("EXEC_NO")).trim();
job.setJobId(ObjectUtils.toString(jobMap.get("JOB_ID")));
job.setJobName(ObjectUtils.toString(jobMap.get("JOB_NAME")));
job.setJobGroup(ObjectUtils.toString(jobMap.get("JOB_GROUP")));
job.setJobStatus(ObjectUtils.toString(jobMap.get("JOB_STATUS")));
job.setCronExpression(ObjectUtils.toString(jobMap.get("CRON_EXPRESSION")));
job.setDesc(ObjectUtils.toString(jobMap.get("JOB_DESC")));
job.setExecNo(execNo);
job.setDataExchange(dataExchange);
job.setBusinessArea(dataExchange.getBusinessArea());
job.setServiceArea(dataExchange.getServiceArea());
job.setDataProcessAtom(this);
list.add(job);
}
return list;
}
public int queryScheduleJob2acctDataProcessBiz(Map<String, String> params, Map<String, String> commParams, GenericResult result) {
int iRetCode = 0;
try {
iRetCode = FrameDao.doBexCall("queryScheduleJob2acctDataProcessBex", params, commParams, result);
if (iRetCode != FrameErrorCode.ISUCCESS_CODE) {
//错误码:-200273;错误信息:DIA_计划任务信息查询数据操作失败。
throw new AtomException(BusinessPrompt.QUERY_SCHEDULE_JOB_ERROR_CODE, BusinessPrompt.QUERY_SCHEDULE_JOB_ERROR_MSG, FrameworkConstants.BIZ_LVL);
}
} catch (AtomException exception) {
iRetCode = exception.getErrorCode();
}
return iRetCode;
}

其他任务操作

  StdScheduler scheduler =(StdScheduler)ConfigLoadUtil.applicationContext.getBean("schedulerFactoryBean");

/**
* 添加任务,运行
* @param dataExchange
*/

public void addAutoTask(DataExchangeAssembly dataExchange){
try {
//这里获取任务信息数据
List<ScheduleJob> jobList = getJob(dataExchange);
for (ScheduleJob job : jobList) {
TriggerKey triggerKey = TriggerKey.triggerKey(job.getJobName(), job.getJobGroup());
//获取trigger,即在spring配置文件中定义的 bean id="myTrigger"
CronTrigger trigger = (CronTrigger) scheduler.getTrigger(triggerKey);
//不存在,创建一个
if (null == trigger) {
JobDetail jobDetail = JobBuilder.newJob(QuartzJobFactory.class)
.withIdentity(job.getJobName(), job.getJobGroup()).build();
jobDetail.getJobDataMap().put("scheduleJob", job);
//表达式调度构建器
CronScheduleBuilder scheduleBuilder = CronScheduleBuilder.cronSchedule(job
.getCronExpression());
//按新的cronExpression表达式构建一个新的trigger
trigger = TriggerBuilder.newTrigger().withIdentity(job.getJobName(), job.getJobGroup()).withSchedule(scheduleBuilder).build();
scheduler.scheduleJob(jobDetail, trigger);
} else {
// Trigger已存在,那么更新相应的定时设置
//表达式调度构建器
CronScheduleBuilder scheduleBuilder = CronScheduleBuilder.cronSchedule(job
.getCronExpression());
//按新的cronExpression表达式重新构建trigger
trigger = trigger.getTriggerBuilder().withIdentity(triggerKey)
.withSchedule(scheduleBuilder).build();
//按新的trigger重新设置job执行
scheduler.rescheduleJob(triggerKey, trigger);
}
}
}catch (Exception e){
//提示码:-100326;提示信息:DIA_开启任务失败
throw new AtomException(BusinessPrompt.START_SCHEDULE_JOB_FAIL_CODE, BusinessPrompt.START_SCHEDULE_JOB_FAIL_MSG+",详细异常:【"+e.getMessage()+"】", FrameworkConstants.ATOM_LVL);
}
}


/**
* 删除任务(终止任务)
* @param dataExchange
*/

public void removeAutoTask(DataExchangeAssembly dataExchange){
//这里获取任务信息数据
List<ScheduleJob> jobList = getJob(dataExchange);
try {
for (ScheduleJob job : jobList) {
JobKey jobKey = JobKey.jobKey(job.getJobName(), job.getJobGroup());
scheduler.deleteJob(jobKey);
}
}catch (Exception e){
//提示码:-100327;提示信息:DIA_恢复任务失败
throw new AtomException(BusinessPrompt.RESUME_SCHEDULE_JOB_FAIL_CODE, BusinessPrompt.RESUME_SCHEDULE_JOB_FAIL_MSG+",详细信息【"+e.getMessage()+"】", FrameworkConstants.ATOM_LVL);
}
}

/**
* 开启任务
* @param dataExchange
*/

public void execAutoTask(DataExchangeAssembly dataExchange) {
removeAutoTask(dataExchange);
addAutoTask(dataExchange);
}

/**
* 恢复任务
* @param dataExchange
*/

public void resumeAutoTask(DataExchangeAssembly dataExchange){
//这里获取任务信息数据
List<ScheduleJob> jobList = getJob(dataExchange);
try {
for (ScheduleJob job : jobList) {
JobKey jobKey = JobKey.jobKey(job.getJobName(), job.getJobGroup());
scheduler.resumeJob(jobKey);
}
}catch (Exception e){
//提示码:-100327;提示信息:DIA_恢复任务失败
throw new AtomException(BusinessPrompt.RESUME_SCHEDULE_JOB_FAIL_CODE, BusinessPrompt.RESUME_SCHEDULE_JOB_FAIL_MSG+",详细信息【"+e.getMessage()+"】", FrameworkConstants.ATOM_LVL);
}
}

/**
* 暂停任务
* @param dataExchange
*/

public void stopAutoTask(DataExchangeAssembly dataExchange) {
//这里获取任务信息数据
List<ScheduleJob> jobList = getJob(dataExchange);
try {
for (ScheduleJob job : jobList) {
JobKey jobKey = JobKey.jobKey(job.getJobName(), job.getJobGroup());
scheduler.pauseJob(jobKey);
}
}catch (Exception e){
//提示码:-100323;提示信息:DIA_暂停任务失败
throw new AtomException(BusinessPrompt.STOP_SCHEDULE_JOB_FAIL_CODE, BusinessPrompt.STOP_SCHEDULE_JOB_FAIL_MSG+",详细信息【"+e.getMessage()+"】", FrameworkConstants.ATOM_LVL);
}
}

/**
* 获取已经添加到quartz调度器的任务(计划中的任务)
* @param dataExchange
*/

public List<ScheduleJob> qryToDoTasks(DataExchangeAssembly dataExchange) {
List<ScheduleJob> jobList = new ArrayList<ScheduleJob>();
try {
GroupMatcher<JobKey> matcher = GroupMatcher.anyJobGroup();
Set<JobKey> jobKeys = scheduler.getJobKeys(matcher);
for (JobKey jobKey : jobKeys) {
List<? extends Trigger> triggers = scheduler.getTriggersOfJob(jobKey);
for (Trigger trigger : triggers) {
ScheduleJob job = new ScheduleJob();
job.setJobName(jobKey.getName());
job.setJobGroup(jobKey.getGroup());
job.setDesc("触发器:" + trigger.getKey());
Trigger.TriggerState triggerState = scheduler.getTriggerState(trigger.getKey());
job.setJobStatus(triggerState.name());
if (trigger instanceof CronTrigger) {
CronTrigger cronTrigger = (CronTrigger) trigger;
String cronExpression = cronTrigger.getCronExpression();
job.setCronExpression(cronExpression);
}
jobList.add(job);
}
}
}catch (Exception e){
//提示码:-100324;提示信息:DIA_查询计划中的任务失败
throw new AtomException(BusinessPrompt.QUERY_TODO_SCHEDULE_JOB_FAIL_CODE, BusinessPrompt.QUERY_TODO_SCHEDULE_JOB_FAIL_MSG+",详细异常:【"+e.getMessage()+"】", FrameworkConstants.ATOM_LVL);
}finally {
return jobList;
}
}

/**
* 获取运行中的任务(这里的运行中是正在调用对应的接口)
* @param dataExchange
* @return
*/

public List<ScheduleJob> qryDoingTasks(DataExchangeAssembly dataExchange) {
List<ScheduleJob> jobList = new ArrayList<ScheduleJob>();
try {
List<JobExecutionContext> executingJobs = scheduler.getCurrentlyExecutingJobs();
jobList = new ArrayList<ScheduleJob>(executingJobs.size());
for (JobExecutionContext executingJob : executingJobs) {
ScheduleJob job = new ScheduleJob();
JobDetail jobDetail = executingJob.getJobDetail();
JobKey jobKey = jobDetail.getKey();
Trigger trigger = executingJob.getTrigger();
job.setJobName(jobKey.getName());
job.setJobGroup(jobKey.getGroup());
job.setDesc("触发器:" + trigger.getKey());
Trigger.TriggerState triggerState = scheduler.getTriggerState(trigger.getKey());
job.setJobStatus(triggerState.name());
if (trigger instanceof CronTrigger) {
CronTrigger cronTrigger = (CronTrigger) trigger;
String cronExpression = cronTrigger.getCronExpression();
job.setCronExpression(cronExpression);
}
jobList.add(job);
}
}catch (Exception e){
//提示码:-100325;提示信息:DIA_查询运行中的任务失败
throw new AtomException(BusinessPrompt.QUERY_DOING_SCHEDULE_JOB_FAIL_CODE, BusinessPrompt.QUERY_DOING_SCHEDULE_JOB_FAIL_MSG+",详细异常:【"+e.getMessage()+"】", FrameworkConstants.ATOM_LVL);
}finally {
return jobList;
}
}

public GenericResult startScheduleJob2acctDataProcess(DataExchangeAssembly dataExchange) {
try {
if("0".equals(autoTaskSwitch)){
throw new AtomException(BusinessPrompt.COLSED_SCHEDULE_JOB_FAIL_CODE, BusinessPrompt.COLSED_SCHEDULE_JOB_FAIL_MSG, FrameworkConstants.ATOM_LVL);
}
Map<String, String> params = (Map<String, String>) dataExchange.getBusinessData("params");
Map<String, String> commParams = (Map<String, String>) dataExchange.getBusinessData("commParams");
int iRetCode = 0;
Uresult result = new Uresult();
params.put("JOB_STATUS","1");
iRetCode = dataProcessBiz.updateScheduleJob2acctDataProcessBiz(params, commParams, result);
if (iRetCode != FrameErrorCode.ISUCCESS_CODE) {
//提示码:-100320;提示信息:DIA_计划任务信息修改失败
throw new AtomException(BusinessPrompt.UPDATE_SCHEDULE_JOB_FAIL_CODE, BusinessPrompt.UPDATE_SCHEDULE_JOB_FAIL_MSG, FrameworkConstants.ATOM_LVL);
}
execAutoTask(dataExchange);
//提示码:0;提示信息:DIA_计划任务信息删除成功
return new AtomResult(BusinessPrompt.ATOM_SUC_CODE, BusinessPrompt.DELETE_SCHEDULE_JOB_SUC_MSG, result.getDataList());
} catch (AtomException exception) {
return new AtomResult(exception.getErrorCode(), exception.getMessage());
}
}