SprinBoot整合Quart实现定时调度的示例代码
Quartz是一款开源的定时任务调度框架,Quartz的官网是:http://www.quartz-scheduler.org/。本文主要是讲诉使用springboot整合quartz实现定时任务调度管理的用例。主要的内容有如下三部分:
1.springboot整合quartz的相关配置
2.实现基于simpleTrigger的定时任务
3.实现基于cronTrigger的定时任务
一、导入相关的pom依赖
4.0.0 com.bruce.quartz.springboot.demo Quartz-SpringBoot-0426 1.0-SNAPSHOT org.springframework.boot spring-boot-starter-parent 1.5.2.RELEASE org.springframework.boot spring-boot-starter-web org.springframework.boot spring-boot-starter-tomcat provided org.springframework.boot spring-boot-starter-test test org.quartz-scheduler quartz 2.2.1 org.quartz-scheduler quartz-jobs 2.2.1 org.springframework.boot spring-boot-maven-plugin
二、创建SpringBoot的启动类
packagecom.anhong; importorg.quartz.Scheduler; importorg.quartz.SchedulerException; importorg.quartz.SchedulerFactory; importorg.quartz.impl.StdSchedulerFactory; importorg.springframework.boot.SpringApplication; importorg.springframework.boot.autoconfigure.SpringBootApplication; importorg.springframework.context.annotation.Bean; /** *@BelongsProject:Quartz-SpringBoot-0426 *@BelongsPackage:com.anhong *@Author:anhong *@CreateTime:2020-10-2409:24 *@Description:TODO */ @SpringBootApplication publicclassAPP{ publicstaticvoidmain(String[]args){ SpringApplication.run(APP.class,args); } /** *向Spring容器中初始注入scheduler */ @Bean publicSchedulerscheduler()throwsSchedulerException{ SchedulerFactoryschedulerFactoryBean=newStdSchedulerFactory(); returnschedulerFactoryBean.getScheduler(); } }
三、创建quartz的作业类
packagecom.anhong.job; importorg.quartz.Job; importorg.quartz.JobExecutionContext; importorg.quartz.JobExecutionException; importjava.text.SimpleDateFormat; importjava.util.Date; /** *@BelongsProject:Quartz-SpringBoot-0426 *@BelongsPackage:com.anhong.job *@Author:anhong *@CreateTime:2020-10-2409:35 *@Description:任务类,实现JOB接口,重写其中的方法 */ publicclassMyJobimplementsJob{ @Override publicvoidexecute(JobExecutionContextcontext)throwsJobExecutionException{ SimpleDateFormatsimpleDateFormat=newSimpleDateFormat("yyyy-MM-ddhh:mm:ss"); Stringtime=simpleDateFormat.format(newDate()); System.out.println("各位老铁,早上好!节日快乐啊!"+time); } }
四、创建quartz的配置类
packagecom.anhong.config; importcom.anhong.bean.TaskInfo; importcom.bruce.job.MyJob; importorg.quartz.*; importorg.quartz.impl.matchers.GroupMatcher; importorg.springframework.beans.factory.annotation.Autowired; importorg.springframework.boot.SpringBootConfiguration; importjavax.annotation.Resource; importjava.util.ArrayList; importjava.util.Date; importjava.util.List; importjava.util.Set; /** *@BelongsProject:Quartz-SpringBoot-0426 *@BelongsPackage:com.anhong.config *@Author:anhong *@CreateTime:2020-10-2410:10 *@Description:Quartz配置类 */ @SpringBootConfiguration publicclassQuartzConfig{ //任务调度器 @Autowired privateSchedulerscheduler; /** *01-开启任务 */ publicvoidstartJob(){ try{ openJob(scheduler); //启动任务 scheduler.start(); }catch(SchedulerExceptione){ e.printStackTrace(); } } /** *02-暂停某个任务 */ publicvoidpauseJob(Stringname,Stringgroup)throwsException{ //任务的标识类 JobKeyjobKey=newJobKey(name,group); JobDetailjobDetail=scheduler.getJobDetail(jobKey); if(jobDetail!=null){ //暂停某个任务 scheduler.pauseJob(jobKey); }else{ System.out.println("该任务不存在!"); } } /** *03-查询所有的任务基本信息 *@return */ publicListgetAllJobsInfo()throwsException{ List list=newArrayList (); //所有任务组 List jobGroupNames=scheduler.getJobGroupNames(); for(StringjobGroupName:jobGroupNames){ Set jobKeys=scheduler.getJobKeys(GroupMatcher. groupEquals(jobGroupName)); for(JobKeyjobKey:jobKeys){ Listtriggers=scheduler.getTriggersOfJob(jobKey); for(Triggertrigger:triggers){ Trigger.TriggerStatetriggerState=scheduler.getTriggerState(trigger.getKey()); JobDetailjobDetail=scheduler.getJobDetail(jobKey); StringcronExpression="";//cron表达式 StringcronDescription="";//描述信息 if(triggerinstanceofCronTrigger){ CronTriggercronTrigger=(CronTrigger)trigger; //cron表达式 cronExpression=cronTrigger.getCronExpression(); cronDescription=cronTrigger.getDescription(); } TaskInfotaskInfo=newTaskInfo(); taskInfo.setJobName(jobKey.getName()); taskInfo.setJobGroup(jobKey.getGroup()); taskInfo.setJobDescrption(jobDetail.getDescription()); taskInfo.setStatus(triggerState.name());//任务的状态 taskInfo.setCronExpression(cronExpression); taskInfo.setCronDescription(cronDescription); list.add(taskInfo); } } } returnlist; } /** *开启一个任务 *@paramscheduler */ privatevoidopenJob(Schedulerscheduler){ try{ //1.创建一个JobDetail JobDetailjobDetail=JobBuilder.newJob(MyJob.class).withIdentity("job1","group1").build(); //2.触发器表达式对象 CronScheduleBuildercronScheduleBuilder=CronScheduleBuilder.cronSchedule("0/4****?"); //CronScheduleBuildercronScheduleBuilder=CronScheduleBuilder.cronSchedule("302516**?"); //3.准备一个触发器对象 CronTriggercronTrigger=TriggerBuilder.newTrigger().withIdentity("trigger1","triggergroup1") .withSchedule(cronScheduleBuilder).build(); //4.开始调度 scheduler.scheduleJob(jobDetail,cronTrigger); }catch(SchedulerExceptione){ e.printStackTrace(); }finally{ } } /** *04-恢复某个任务的执行 *@paramname *@paramgroup */ publicvoidresumeJob(Stringname,Stringgroup)throwsException{ JobKeyjobKey=newJobKey(name,group); JobDetailjobDetail=scheduler.getJobDetail(jobKey); if(jobDetail!=null){ scheduler.resumeJob(jobKey); }else{ System.out.println("要恢复的任务不存在!"); } } /** *05-删除某一个任务 *@paramname *@paramgroup *@throwsException */ publicvoiddeleteJob(Stringname,Stringgroup)throwsException{ JobKeyjobKey=newJobKey(name,group); JobDetailjobDetail=scheduler.getJobDetail(jobKey); if(jobDetail!=null){ scheduler.deleteJob(jobKey); }else{ System.out.println("要删除的任务不存在!"); } } /** *06-动态的修改任务执行的表达式,触发规则 *@paramname *@paramgroup *@return */ publicbooleanmodifyJob(Stringname,Stringgroup,StringnewTime)throwsException{ Datedate=null; TriggerKeytriggerKey=newTriggerKey(name,group); Triggertrigger=scheduler.getTrigger(triggerKey); CronTriggercronTrigger=null; if(triggerinstanceofCronTrigger){ cronTrigger=(CronTrigger)trigger; //表达式 StringcronExpression=cronTrigger.getCronExpression(); if(!cronExpression.equalsIgnoreCase(newTime)){ System.out.println("需要修改原来的表达式:"+cronExpression+"为:"+newTime); CronScheduleBuildercronScheduleBuilder=CronScheduleBuilder.cronSchedule(newTime); //新的触发器 CronTriggercronTrigger1=TriggerBuilder.newTrigger().withIdentity(name,group).withSchedule(cronScheduleBuilder).build(); date=scheduler.rescheduleJob(triggerKey,cronTrigger1); }else{ System.out.println("不用修改!和原来的一样!"); } } if(date!=null){ returntrue; }else{ returnfalse; } } }
任务对象
packagecom.anhong.bean; /** *@BelongsProject:Quartz-SpringBoot-0426 *@BelongsPackage:com.anhong.bean *@Author:anhong *@CreateTime:2020-10-2410:24 *@Description:任务对象 */ publicclassTaskInfo{ privateStringjobName; privateStringjobGroup; privateStringjobDescrption; privateStringstatus; privateStringcronExpression; privateStringcronDescription; publicStringgetJobName(){ returnjobName; } publicvoidsetJobName(StringjobName){ this.jobName=jobName; } publicStringgetJobGroup(){ returnjobGroup; } publicvoidsetJobGroup(StringjobGroup){ this.jobGroup=jobGroup; } publicStringgetJobDescrption(){ returnjobDescrption; } publicvoidsetJobDescrption(StringjobDescrption){ this.jobDescrption=jobDescrption; } publicStringgetStatus(){ returnstatus; } publicvoidsetStatus(Stringstatus){ this.status=status; } publicStringgetCronExpression(){ returncronExpression; } publicvoidsetCronExpression(StringcronExpression){ this.cronExpression=cronExpression; } publicStringgetCronDescription(){ returncronDescription; } publicvoidsetCronDescription(StringcronDescription){ this.cronDescription=cronDescription; } }
五、创建Quartz的监听类
packagecom.anhong; importorg.quartz.Scheduler; importorg.quartz.SchedulerException; importorg.quartz.SchedulerFactory; importorg.quartz.impl.StdSchedulerFactory; importorg.springframework.beans.factory.annotation.Autowired; importorg.springframework.context.ApplicationListener; importorg.springframework.context.annotation.Bean; importorg.springframework.context.annotation.Configuration; importorg.springframework.context.event.ContextRefreshedEvent; @Configuration publicclassApplicationStartQuartzJobListenerimplementsApplicationListener{ @Autowired privateQuartzSchedulerquartzScheduler; /** *初始启动quartz */ @Override publicvoidonApplicationEvent(ContextRefreshedEventevent){ try{ quartzScheduler.startJob(); System.out.println("任务已经启动..."); }catch(SchedulerExceptione){ e.printStackTrace(); } } /** *初始注入scheduler *@return *@throwsSchedulerException */ @Bean publicSchedulerscheduler()throwsSchedulerException{ SchedulerFactoryschedulerFactoryBean=newStdSchedulerFactory(); returnschedulerFactoryBean.getScheduler(); } }
六、创建控制器
packagecom.anhong.controller; importcom.anhong.bean.TaskInfo; importcom.anhong.config.QuartzConfig; importorg.springframework.beans.factory.annotation.Autowired; importorg.springframework.web.bind.annotation.RequestMapping; importorg.springframework.web.bind.annotation.RestController; importjava.util.List; /** *@BelongsProject:Quartz-SpringBoot-0426 *@BelongsPackage:com.anhong.controller *@Author:anhong *@CreateTime:2020-10-2410:43 *@Description:TODO */ @RestController @RequestMapping("/quartz") publicclassQuartzController{ @Autowired QuartzConfigquartzConfig; /** *01-开启一个定时任务 * *@return */ @RequestMapping("/start") publicStringstartQuartzJob(){ try{ quartzConfig.startJob(); }catch(Exceptione){ e.printStackTrace(); return"定时任务开启异常~~~"; } return"定时任务开启成功~~~"; } /** *02-暂停任务 * *@paramname *@paramgroup *@return */ @RequestMapping("/pauseJob") publicStringpauseJob(Stringname,Stringgroup){ try{ quartzConfig.pauseJob(name,group); }catch(Exceptione){ e.printStackTrace(); returnname+"任务暂停异常"; }finally{ } returnname+"任务被暂停"; } /** *03-查询所有的任务基本信息 * *@return */ @RequestMapping("/infos") publicListgetAllJobsInfo(){ try{ returnquartzConfig.getAllJobsInfo(); }catch(Exceptione){ e.printStackTrace(); } returnnull; } /** *04-恢复某个任务的执行 * *@paramname *@paramgroup */ @RequestMapping("/resumeJob") publicStringresumeJob(Stringname,Stringgroup){ try{ quartzConfig.resumeJob(name,group); }catch(Exceptione){ e.printStackTrace(); returnname+"任务被恢复异常!"; }finally{ } returnname+"任务被恢复啦!"; } /** *05-删除某一个任务 * *@paramname *@paramgroup *@throwsException */ @RequestMapping("/deleteJob") publicStringdeleteJob(Stringname,Stringgroup){ try{ quartzConfig.deleteJob(name,group); }catch(Exceptione){ e.printStackTrace(); returnname+"任务删除异常!"; }finally{ } returnname+"任务被删除啦!"; } /** *06-动态的修改任务执行的表达式,触发规则 * *@paramname *@paramgroup *@return */ @RequestMapping("/modifyJob") publicStringmodifyJob(Stringname,Stringgroup,StringnewTime){ booleanflag=false; try{ flag=quartzConfig.modifyJob(name,group,newTime); }catch(Exceptione){ e.printStackTrace(); }finally{ } if(flag){ returnname+"任务时间表达式修改为:"+newTime; }else{ returnname+"任务时间表达式失败!"; } } }
总结:SpringBoot整合Quertz实现定时调度的大致步骤实现就如上,在很多微服务商城项目上都会用到定时调度,在根据实际的项目业务需要,我们只需要把以上的一些配置做适当的修改来满足自己业务的需要。
到此这篇关于SprinBoot整合Quart实现定时调度的示例代码的文章就介绍到这了,更多相关SprinBoot整合Quart内容请搜索毛票票以前的文章或继续浏览下面的相关文章希望大家以后多多支持毛票票!