添加依赖
<dependency>
<groupId>org.quartz-scheduler</groupId>
<artifactId>quartz</artifactId>
<version>2.3.0</version>
</dependency>
<dependency>
<groupId>org.quartz-scheduler</groupId>
<artifactId>quartz-jobs</artifactId>
<version>2.3.0</version>
</dependency>
1.监听类
我们是将定时相关配置会放入到相关数据库中;
/**
* @Auther: jdl
* @Date: 2021-03-09
* @Description:
*/
@WebListener
public class CodeTransListener implements ServletContextListener{
private Logger logger = LoggerFactory.getLogger(CodeTransListener.class);
@Autowired
private JoblogMapper joblogMapper;
@Autowired
private SchedulerJobService schedulerJobService;
@Override
public void contextInitialized(ServletContextEvent servletContextEvent) {
ServletContext sc = servletContextEvent.getServletContext();
System.out.println("启动");
getBasicInfo();
System.out.println("导入完成!");
}
@Override
public void contextDestroyed(ServletContextEvent servletContextEvent) {
System.out.println("终止");
}
/*
*
* 项目初始化加载定时任务*/
public void getBasicInfo(){
JobinfoReq jobbean = new JobinfoReq();
jobbean.setStatus("1");
List<Jobinfo> jobbeanlist = joblogMapper.selectjoninfolist(jobbean);
for(Jobinfo job : jobbeanlist){
JobinfoReq jobinfoReq = new JobinfoReq();
jobinfoReq.setJobflag("1");
jobinfoReq.setJobClassName("cn.etib.law.controller.ApiJob");
jobinfoReq.setJobGroup(job.getOrgcode()+"_"+job.getCaldate());
jobinfoReq.setCronexpre(job.getCronexpre());
jobinfoReq.setJobname(job.getJobname());
jobinfoReq.setOrgcode(job.getOrgcode());
jobinfoReq.setOrgname(job.getOrgname());
jobinfoReq.setId(job.getId());
jobinfoReq.setCaldate(job.getCaldate());
jobinfoReq.setListennerflag("1");
try {
int i = schedulerJobService.saveOrUpdate(jobinfoReq);
} catch (Exception e) {
e.printStackTrace();
}
}
System.out.println("初始化入参");
System.out.println("初始化加载已有定时任务完成");
}
}
2.抽取的service
int saveOrUpdate(JobinfoReq scheduleJob) throws Exception;
public int saveOrUpdate(JobinfoReq scheduleJob) throws Exception {
int flag = 0;
if (scheduleJob.getJobflag().equals("1")){
logger.info("添加任务----------------/addJob");
addJob(scheduleJob);
flag = 1;
}else {
logger.info("更新任务----------------/updateJob");
updateJobSchedule(scheduleJob);
}
return flag;
}
private void addJob(JobinfoReq scheduleJob) throws Exception{
logger.info("cron表达式:" + scheduleJob.getCronexpre());
scheduleJob.setCronExpression(scheduleJob.getCronexpre());
scheduleJob.setTriggerName("trigger" + scheduleJob.getJobname());
scheduleJob.setTriggerGroup(scheduleJob.getJobGroup());
scheduleJob.setJobStatus("1");
scheduleJob.setJobRunState("0");
//构建job信息
JobDetail jobDetail = JobBuilder.newJob(getCls(scheduleJob.getJobClassName()).getClass())
.withIdentity(scheduleJob.getJobGroup(),scheduleJob.getJobGroup())
.withDescription(scheduleJob.getJobname())
.build();
jobDetail.getJobDataMap().put("scheduleJob",scheduleJob);
//表达式调度构建器(即任务执行的时间)
CronScheduleBuilder cronScheduleBuilder = CronScheduleBuilder.cronSchedule(scheduleJob.getCronexpre());
//按新的cronExpression表达式构建一个新的trigger
CronTrigger cronTrigger = TriggerBuilder.newTrigger()
.withIdentity(scheduleJob.getJobGroup(),scheduleJob.getJobGroup())
.withSchedule(cronScheduleBuilder).build();
//传递的参数
jobDetail.getJobDataMap().put("jobTaskType", "0");
jobDetail.getJobDataMap().put("caldate", scheduleJob.getCaldate());
jobDetail.getJobDataMap().put("orgcode", scheduleJob.getOrgcode());
jobDetail.getJobDataMap().put("id", scheduleJob.getId());
//交由Scheduler安排触发
TriggerKey triggerKey = TriggerKey.triggerKey(scheduleJob.getJobGroup(),scheduleJob.getJobGroup());
CronTrigger cronTriggerTemp = (CronTrigger) scheduler.getTrigger(triggerKey);
if (cronTrigger==null){
logger.info("添加任务");
scheduler.scheduleJob(jobDetail,cronTrigger);
}else{
logger.info("已存在");
}
if(scheduleJob.getListennerflag() == null || !scheduleJob.getListennerflag().equals("1")){
schedulerJobInService.insertSelective(scheduleJob);
}
}
3.封装quartz执行
public interface BaseJob extends Job {
public void execute(JobExecutionContext context) throws JobExecutionException;
}
@Service
public class ApiJob implements BaseJob{
private Logger logger = LoggerFactory.getLogger(ApiJob.class);
@Autowired
private BaseManageClient baseManageClient;
@Autowired
private JoblogMapper joblogMapper;
@Override
public void execute(JobExecutionContext context) throws JobExecutionException {
// 取得job详情
JobDetail jobDetail = context.getJobDetail();
// 取得job名称
String jobName = jobDetail.getKey().getName();
String jobGroup = jobDetail.getKey().getGroup();
logger.info("=========定时任务 | 任务分组:" + jobGroup + ",任务名称:" + jobName + ",调用接口服务执行开始=========");
logger.info("定时任务名称: " + jobName);
// 取得job的类
String cls = jobDetail.getJobClass().getName();
logger.info("定时任务执行类名: " + cls);
// 取得jobgroup名称
logger.info("任务组名: " + jobGroup);
// 取得job开始时间
Date fireTime = context.getFireTime();
String fireTimeStr = DateUtil.formatDate(fireTime, DateUtil.YEAR_TO_SECOND);
logger.info(jobName + " 开始时间: " + fireTimeStr);
JobDataMap dataMap = jobDetail.getJobDataMap();
String orgcode = dataMap.getString("orgcode");
String caldate = dataMap.getString("caldate");
String id = dataMap.getString("id");
JobinfoReq job = new JobinfoReq();
job.setId(id);
//获取本批次任务id
List<Jobinfo> joblist = joblogMapper.selectjoninfolist(job);
if(joblist.size() == 1 && joblist.get(0) != null){
if(joblist.get(0).getExecutestatus().equals(0)){
//0未执行,1执行中,2已执行完毕
logger.info("jobTaskType: " + orgcode);
logger.info("jobType: " + caldate);
logger.info("apiUrl: " + id);
try {
//异步执行每个任务
TimmingInfo timinfo = new TimmingInfo();
timinfo.setBranchOrgCode(orgcode);
timinfo.setSettlement(caldate);
timinfo.setId(id);
baseManageClient.executeJob(JSON.toJSONString(timinfo));
logger.info("定时任务接口调用执行参数:"+JSON.toJSONString(timinfo));
} catch (Exception e) {
logger.info("接口异常");
e.printStackTrace();
}
}
}
}
}