quartz和spring集成使用一例子【我】
首先在spring配置文件中增加:
<!-- 调度器 --> <bean name="scheduler" lazy-init="false" autowire="no" class="org.springframework.scheduling.quartz.SchedulerFactoryBean"> <property name="applicationContextSchedulerContextKey" value="applicationContextKey" /> <property name="quartzProperties"><!-- 需要添加的内容配置 --> <props> <prop key="org.quartz.scheduler.skipUpdateCheck">true</prop> </props> </property> </bean> <bean name="jobManager" class="com.xxx.crm.schedule.JobManager" init-method="init" destroy-method="close"> <property name="scheduler" ref="scheduler"/> </bean>
定时任务公共抽象类:
/* * @author junsheng * @date 2018年8月13日 上午1:59:48 * @Description: 此处添加文件描述…… */ import java.util.List; import java.util.Map; import java.util.Set; import org.quartz.CronScheduleBuilder; import org.quartz.CronTrigger; import org.quartz.Job; import org.quartz.JobBuilder; import org.quartz.JobDetail; import org.quartz.JobKey; import org.quartz.Scheduler; import org.quartz.SchedulerException; import org.quartz.TriggerBuilder; import org.quartz.impl.matchers.GroupMatcher; public abstract class AbstractScheduler { public void scheduleJob(String name, String group, String cronExpression, Class<? extends Job> jobClass, Map<String, Object> jobParam) throws Exception { JobDetail jobDetail = JobBuilder.newJob(jobClass).withIdentity(name, group).build(); if (jobParam != null) { jobDetail.getJobDataMap().putAll(jobParam); } CronTrigger trigger = (CronTrigger) TriggerBuilder.newTrigger().withIdentity(name, group).withSchedule(CronScheduleBuilder.cronSchedule(cronExpression)).build(); JobKey jobKey = JobKey.jobKey(name, group); try { getScheduler().deleteJob(jobKey); getScheduler().scheduleJob(jobDetail, trigger); getScheduler().start(); } catch (SchedulerException e) { throw e; } } public void deleteJob(String jobName, String jobGroup) throws SchedulerException { JobKey jobKey = JobKey.jobKey(jobName, jobGroup); try { getScheduler().deleteJob(jobKey); } catch (SchedulerException e) { throw e; } } public void deleteAllJob() throws SchedulerException { List<String> groups = getScheduler().getJobGroupNames(); if (groups == null) { return; } for (String group : groups) { Set<JobKey> jobKeys = getScheduler().getJobKeys(GroupMatcher.jobGroupEquals(group)); if (jobKeys != null) { for (JobKey jobKey : jobKeys) { getScheduler().deleteJob(jobKey); } } } } public void deleteGroupAllJob(String groupName) throws SchedulerException { Set<JobKey> jobKeys = getScheduler().getJobKeys(GroupMatcher.jobGroupEquals(groupName)); if (jobKeys == null) { return; } for (JobKey jobKey : jobKeys) { getScheduler().deleteJob(jobKey); } } public abstract Scheduler getScheduler(); }
定时任务具体类:
import java.util.Map; import org.quartz.Job; import org.quartz.Scheduler; import org.quartz.SchedulerException; import org.slf4j.Logger; import org.slf4j.LoggerFactory; import com.xxx.batch.task.BatchBeginJob; import com.xxx.batch.task.BatchEndJob; import com.xxx.common.task.AbstractScheduler; import com.xxx.util.PropertieUtil; public class JobManager extends AbstractScheduler { private static final String JOB_GROUP = "myGroup"; private final Logger log = LoggerFactory.getLogger(JobManager.class); private Scheduler scheduler; public void init() { try { /*******************************初始化调度任务******************************/ // 批量处理定时器 // 每天凌晨1点执行一次:0 0 1 * * ? createOrUpdateJob("batchBengin", PropertieUtil.getConfig("cron.batch.begin"), BatchBeginJob.class); createOrUpdateJob("batchEnd", PropertieUtil.getConfig("cron.batch.end"), BatchEndJob.class); } catch (Exception e) { this.log.error("任务调度JobManager启动失败,异常信息:" + e.getMessage(), e); } } public void close() { try { getScheduler().shutdown(true); } catch (SchedulerException e) { this.log.error(e.getMessage(), e); } } public void deleteJob(String jobName) throws Exception { deleteJob(jobName, "myGroup"); } public void createOrUpdateJob(String jobName, String cronExpression, Class<? extends Job> jobClass) throws Exception { scheduleJob(jobName, "myGroup", cronExpression, jobClass, null); } public void createOrUpdateJob(String jobGroup, String jobName, String cronExpression, Class<? extends Job> jobClass) throws Exception { scheduleJob(jobName, jobGroup, cronExpression, jobClass, null); } public void createOrUpdateJob(String jobName, String cronExpression, Class<? extends Job> jobClass, Map<String, Object> param) throws Exception { scheduleJob(jobName, "myGroup", cronExpression, jobClass, param); } public void createOrUpdateJob(String jobGroup, String jobName, String cronExpression, Class<? extends Job> jobClass, Map<String, Object> param) throws Exception { scheduleJob(jobName, jobGroup, cronExpression, jobClass, param); } @Override public Scheduler getScheduler() { return this.scheduler; } public void setScheduler(Scheduler scheduler) { this.scheduler = scheduler; } }
具体任务执行类:
类1:
import org.quartz.Job; import org.quartz.JobExecutionContext; import org.quartz.JobExecutionException; import org.slf4j.Logger; import org.slf4j.LoggerFactory; import com.xxx.common.task.SpringContext; import com.xxx.schedule.JobManager; import com.xxx.util.PropertieUtil; public class BatchBeginJob implements Job { protected static Logger logger = LoggerFactory.getLogger(BatchBeginJob.class); @Override public void execute(JobExecutionContext context) throws JobExecutionException { //开启循环定时器 JobManager jobManager = (JobManager) SpringContext.getApplicationContext().getBean("jobManager"); try { // 每隔1分钟执行一次:0 */1 * * * ? 每隔5秒执行一次:*/5 * * * * ? jobManager.createOrUpdateJob("batchLoopGroup","batchLoop", PropertieUtil.getConfig("cron.batch.loop"), BatchLoopJob.class); logger.info("****** 启动循环定时器成功 ******"); } catch (Exception e) { e.printStackTrace(); } } }
类2:
import java.util.Map; import org.quartz.DisallowConcurrentExecution; import org.quartz.Job; import org.quartz.JobExecutionContext; import org.quartz.JobExecutionException; import org.slf4j.Logger; import org.slf4j.LoggerFactory; import com.xxx.batch.service.BatchService; import com.xxx.batch.util.BatchConstants; import com.xxx.common.task.SpringContext; import com.xxx.inter.BatchRNeService; import com.xxx.util.Util; @DisallowConcurrentExecution //使任务以单线程方式执行的注解 public class BatchLoopJob implements Job { protected static Logger logger = LoggerFactory.getLogger(BatchLoopJob.class); @Override public void execute(JobExecutionContext context) throws JobExecutionException { //远程处理合规业务接口服务 BatchRNeService batchRNeService = (BatchRNeService)SpringContext.getApplicationContext().getBean("batchRNeService"); //本地查询文档表服务 BatchService batchService = (BatchService) SpringContext.getApplicationContext().getBean("batchServiceImpl"); //记录开始时间 long beginTime = System.currentTimeMillis(); try { Map map = null; //最后查询 状态为 未处理的(STATUS_CD = 1000) map = batchService.queryOneByHandleStatus(BatchConstants.HANDLE_BEFORE); //如果存在, 取第一条即可 if(map!=null) { //调侯彬的接口 logger.info("{}||{}","-------------开始调用处理接口,参数为: ", map.get("haha_ID")); String jsonString = batchRNeService.batchRemoteService(Util.getInterfaceReq(map)); Map<String, Object> responseMap = Util.getJsonResultObject(jsonString); logger.info("{}||{}","-------------批接口返回结果:", responseMap); return; } } catch (Exception e) { e.printStackTrace(); }finally { logger.info("{}||{}","--------------任务耗时:",(System.currentTimeMillis()-beginTime)+" 毫秒"); } } // @Resource //这里用这个注解无效,必须用getBean的方式 // private BatchRNeService batchRNeService; /* public static void main(String[] args) { ApplicationContext context = new ClassPathXmlApplicationContext("classpath:spring-config/disconf.beans.xml"); // BatchService service = (BatchService)context.getBean("batchServiceImpl"); // Map map = service.queryOneByHandleStatus("1100"); BatchRNeService service = (BatchRNeService)context.getBean("batchRNeService"); HashMap<Object, Object> map = new HashMap<>(); map.put("haha_ID", 1); System.out.println("-------------: "+map); String resp = service.batchRemoteService(Util.getInterfaceReq(map)); System.out.println("----------- --: "+resp); // {DOC_NAME=h1, DOC_TYPE=1000, haha_ID=1, STATUS_CD=1100, DOC_REGION_CODE=11} //文件id // String docId = String.valueOf(map.get("haha_ID")); // System.out.println(docId); }*/ }