springboot动态定时任务的实现方法示例
1、maven引入quartz包
org.quartz-scheduler quartz 2.3.2
2、创建定时任务工厂类
/** *定时任务工厂类 */ @Component publicclassJobFactoryextendsSpringBeanJobFactoryimplementsApplicationContextAware{ privatetransientAutowireCapableBeanFactorybeanFactory; @Override protectedObjectcreateJobInstance(TriggerFiredBundlebundle)throwsException{ finalObjectjobInstance=super.createJobInstance(bundle); beanFactory.autowireBean(jobInstance); returnjobInstance; } @Override publicvoidsetApplicationContext(ApplicationContextapplicationContext)throwsBeansException{ this.beanFactory=applicationContext.getAutowireCapableBeanFactory(); } }
3、创建定时任务抽象类
publicabstractclassAbstractTaskimplementsJob{ privateLoggerlogger=LoggerFactory.getLogger(AbstractTask.class); protectedabstractvoidexecuteInternal(JobExecutionContextcontext)throwsException; /** *定时任务标识 */ privateStringkey; /** *数据库里配置的主键id */ privateLongdataBaseId; @Override publicvoidexecute(JobExecutionContextcontext){ try{ executeInternal(context); }catch(Exceptione){ logger.error(e.getMessage(),e); logger.error("jobexecutefailed!"); } } publicStringgetKey(){ returnkey; } publicvoidsetKey(Stringkey){ this.key=key; } publicLonggetDataBaseId(){ returndataBaseId; } publicvoidsetDataBaseId(LongdataBaseId){ this.dataBaseId=dataBaseId; } }
4、创建定时任务业务实现类
这里可以写你的业务代码,实现具体的业务逻辑。
@Component("JobTask") publicclassJobTaskextendsAbstractTask{ @Override protectedvoidexecuteInternal(JobExecutionContextcontext){ System.out.println("key="+this.getKey()); System.out.println("dataBaseId="+this.getDataBaseId()); } }
5、创建定时任务管理器
包括项目启动时添加定时任务,手动添加定时任务,更新定时任务,删除定时任务方法。
/** *定时任务管理容器component(单例模式) */ @Component @Scope("singleton") publicclassJobQuartzManagerimplementsApplicationContextAware{ /** *创建新的scheduler */ privatestaticSchedulerFactoryschedulerFactory=newStdSchedulerFactory(); privateSchedulerscheduler; /** *定义组名称,不同的组用于区分任务 */ privatestaticfinalStringJOB_GROUP_NAME="JOB_GROUP_NAME"; privatestaticfinalStringTRIGGER_GROUP_NAME="TRIGGER_GROUP_NAME"; /** *日志 */ privateLoggerlogger=LoggerFactory.getLogger(JobQuartzManager.class); privateApplicationContextapplicationContext; @Autowired privateJobFactoryjobFactory; publicvoidstart(){ //启动定时任务(初始化) try{ this.scheduler=schedulerFactory.getScheduler(); scheduler.setJobFactory(jobFactory);//设置定时任务工厂模式 //项目启动时默认给spring容器添加动态的定时任务 this.addJob("job"+100L,100L,JobTask.class,"0/2****?"); }catch(SchedulerExceptione){ logger.error(e.getMessage(),e); thrownewRuntimeException("initSchedulerfailed"); } } publicbooleanaddJob(StringjobName,LongdataBaseId,ClassjobClass,StringcronExp){ booleanresult=false; if(!CronExpression.isValidExpression(cronExp)){ logger.error("Illegalcronexpressionformat({})",cronExp); returnresult; } try{ JobDetailjobDetail=JobBuilder.newJob().withIdentity(newJobKey(jobName,JOB_GROUP_NAME)) .ofType((Class)Class.forName(jobClass.getName())) .build(); //创建完jobDetail之后,使用语句传参数值,方便定时任务内部识别它是什么标识 JobDataMapjobDataMap=jobDetail.getJobDataMap(); jobDataMap.put("key",jobName); jobDataMap.put("dataBaseId",dataBaseId); Triggertrigger=TriggerBuilder.newTrigger() .forJob(jobDetail) .withSchedule(CronScheduleBuilder.cronSchedule(cronExp)) .withIdentity(newTriggerKey(jobName,TRIGGER_GROUP_NAME)) .build(); scheduler.scheduleJob(jobDetail,trigger); scheduler.start(); result=true; }catch(Exceptione){ logger.error(e.getMessage(),e); logger.error("QuartzManageraddjobfailed"); } returnresult; } publicbooleanupdateJob(StringjobName,StringcronExp){ booleanresult=false; if(!CronExpression.isValidExpression(cronExp)){ logger.error("Illegalcronexpressionformat({})",cronExp); returnresult; } JobKeyjobKey=newJobKey(jobName,JOB_GROUP_NAME); TriggerKeytriggerKey=newTriggerKey(jobName,TRIGGER_GROUP_NAME); try{ if(scheduler.checkExists(jobKey)&&scheduler.checkExists(triggerKey)){ JobDetailjobDetail=scheduler.getJobDetail(jobKey); TriggernewTrigger=TriggerBuilder.newTrigger() .forJob(jobDetail) .withSchedule(CronScheduleBuilder.cronSchedule(cronExp)) .withIdentity(newTriggerKey(jobName,TRIGGER_GROUP_NAME)) .build(); scheduler.rescheduleJob(triggerKey,newTrigger); result=true; }else{ logger.error("updatejobname:{},groupname:{}ortriggername:{},groupname:{}notexists..", jobKey.getName(),jobKey.getGroup(),triggerKey.getName(),triggerKey.getGroup()); } }catch(SchedulerExceptione){ logger.error(e.getMessage(),e); logger.error("updatejobname:{},groupname:{}failed!",jobKey.getName(),jobKey.getGroup()); } returnresult; } publicbooleandeleteJob(StringjobName){ booleanresult=false; JobKeyjobKey=newJobKey(jobName,JOB_GROUP_NAME); try{ if(scheduler.checkExists(jobKey)){ result=scheduler.deleteJob(jobKey); }else{ logger.error("deletejobname:{},groupname:{}notexists.",jobKey.getName(),jobKey.getGroup()); } }catch(SchedulerExceptione){ logger.error(e.getMessage(),e); logger.error("deletejobname:{},groupname:{}failed!",jobKey.getName(),jobKey.getGroup()); } returnresult; } @Override publicvoidsetApplicationContext(ApplicationContextapplicationContext)throwsBeansException{ this.applicationContext=applicationContext; } }
6、创建定时任务启动类
项目运行时给spring注入定时任务
/** *定时任务启动类 */ @Component publicclassJobRunnerimplementsApplicationRunner{ //注入定时任务管理器 @Autowired privateJobQuartzManagerquartzManager; /** *项目启动时激活定时任务 */ @Override publicvoidrun(ApplicationArgumentsapplicationArguments){ System.out.println("--------------------注入定时任务---------------------"); quartzManager.start(); System.out.println("--------------------定时任务注入完成---------------------"); } }
7、测试案例
@RestController @RequestMapping("/job") publicclassJobController{ @Autowired JobQuartzManagerquartzManager; @PostMapping("addJob") @ResponseBody publicStringaddJob(@RequestParam("dataBaseId")LongdataBaseId,@RequestParam("cronExp")StringcronExp){ booleansuccess=quartzManager.addJob("job"+dataBaseId,dataBaseId,JobTask.class,cronExp); if(success){ return"添加成功"; }else{ return"添加失败!"; } } @PostMapping("deleteJob") @ResponseBody publicStringdeleteJob(@RequestParam("jobName")StringjobName){ booleansuccess=quartzManager.deleteJob(jobName); if(success){ return"删除成功"; }else{ return"删除失败!"; } } @PostMapping("updateJob") @ResponseBody publicStringupdateJob(@RequestParam("jobName")StringjobName,@RequestParam("cronExp")StringcronExp){ booleansuccess=quartzManager.updateJob(jobName,cronExp); if(success){ return"更新成功"; }else{ return"更新失败!"; } } }
总结
到此这篇关于springboot实现动态定时任务的文章就介绍到这了,更多相关springboot动态定时任务内容请搜索毛票票以前的文章或继续浏览下面的相关文章希望大家以后多多支持毛票票!
声明:本文内容来源于网络,版权归原作者所有,内容由互联网用户自发贡献自行上传,本网站不拥有所有权,未作人工编辑处理,也不承担相关法律责任。如果您发现有涉嫌版权的内容,欢迎发送邮件至:czq8825#qq.com(发邮件时,请将#更换为@)进行举报,并提供相关证据,一经查实,本站将立刻删除涉嫌侵权内容。