摘要:本文使用實現對定時任務的增刪改查啟用停用等功能。并把定時任務持久化到數據庫以及支持集群。決定什么時候來執行任務。定義的是任務數據,而真正的執行邏輯是在中。封裝定時任務接口添加一個暫停恢復刪除修改暫停所有恢復所有
簡介
Quartz是一款功能強大的任務調度器,可以實現較為復雜的調度功能,如每月一號執行、每天凌晨執行、每周五執行等等,還支持分布式調度。本文使用Springboot+Mybatis+Quartz實現對定時任務的增、刪、改、查、啟用、停用等功能。并把定時任務持久化到數據庫以及支持集群。對于如何創建Springboot項目和與Mybatis整合可以參考上篇文章:[spring-boot整合Mybatis如何部署在weblogic上
][1]。
Scheduler:調度器。所有的調度都是由它控制。
Trigger: 觸發器。決定什么時候來執行任務。
JobDetail & Job: JobDetail定義的是任務數據,而真正的執行邏輯是在Job中。使用JobDetail + Job而不是Job,這是因為任務是有可能并發執行,如果Scheduler直接使用Job,就會存在對同一個Job實例并發訪問的問題。而JobDetail & Job 方式,sheduler每次執行,都會根據JobDetail創建一個新的Job實例,這樣就可以規避并發訪問的問題。
如何使用Quartz添加依賴
org.quartz-scheduler quartz 2.2.3 org.quartz-scheduler quartz-jobs 2.2.3
2.創建配置文件
在maven項目的resource目錄下創建quartz.properties
org.quartz.scheduler.instanceName = MyScheduler org.quartz.scheduler.instanceId = AUTO org.quartz.scheduler.rmi.export = false org.quartz.scheduler.rmi.proxy = false org.quartz.scheduler.wrapJobExecutionInUserTransaction = false #線程池配置 org.quartz.threadPool.class = org.quartz.simpl.SimpleThreadPool org.quartz.threadPool.threadCount = 10 org.quartz.threadPool.threadPriority = 5 org.quartz.threadPool.threadsInheritContextClassLoaderOfInitializingThread = true #持久化配置 org.quartz.jobStore.misfireThreshold = 50000 org.quartz.jobStore.class = org.quartz.impl.jdbcjobstore.JobStoreTX #支持集群 org.quartz.jobStore.isClustered = true org.quartz.jobStore.useProperties:true org.quartz.jobStore.clusterCheckinInterval = 15000 #使用weblogic連接Oracle驅動 org.quartz.jobStore.driverDelegateClass = org.quartz.impl.jdbcjobstore.oracle.weblogic.WebLogicOracleDelegate #org.quartz.jobStore.driverDelegateClass = org.quartz.impl.jdbcjobstore.StdJDBCDelegate org.quartz.jobStore.tablePrefix = QRTZ_ org.quartz.jobStore.dataSource = qzDS #數據源連接信息,quartz默認使用c3p0數據源可以被自定義數據源覆蓋 org.quartz.dataSource.qzDS.driver = oracle.jdbc.driver.OracleDriver org.quartz.dataSource.qzDS.URL = jdbc:oracle:thin:@localhost:1521/XE org.quartz.dataSource.qzDS.user = root org.quartz.dataSource.qzDS.password = 123456 org.quartz.dataSource.qzDS.maxConnections = 10
說明:在使用quartz做持久化的時候需要用到quartz的11張表,可以去quartz官網下載對應版本的quartz,解壓打開docs/dbTables里面有對應數據庫的建表語句。關于quartz.properties配置的詳細解釋可以查看quartz官網。另外新建一張表TB_APP_QUARTZ用于存放定時任務基本信息和描述等信息,定時任務的增、刪、改、執行等功能與此表沒有任何關系。
quartz的11張表:
//TB_APP_QUARTZ表的實體類 public class AppQuartz { private Integer quartzId; //id 主鍵 private String jobName; //任務名稱 private String jobGroup; //任務分組 private String startTime; //任務開始時間 private String cronExpression; //corn表達式 private String invokeParam;//需要傳遞的參數 ...省略set get }
3.Quartz配置
/** * 創建job 實例工廠,解決spring注入問題,如果使用默認會導致spring的@Autowired 無法注入問題 * @author LLQ * */ @Component public class JobFactory extends AdaptableJobFactory{ @Autowired private AutowireCapableBeanFactory capableBeanFactory; @Override protected Object createJobInstance(TriggerFiredBundle bundle) throws Exception { //調用父類的方法 Object jobInstance = super.createJobInstance(bundle); //進行注入 capableBeanFactory.autowireBean(jobInstance); return jobInstance; } }
@Configuration public class SchedulerConfig implements ApplicationListener{ @Autowired private JobFactory jobFactory; @Autowired @Qualifier("dataSource") private DataSource primaryDataSource; @Override public void onApplicationEvent(ContextRefreshedEvent event) { System.out.println("任務已經啟動..."+event.getSource()); } @Bean public SchedulerFactoryBean schedulerFactoryBean() throws IOException { //獲取配置屬性 PropertiesFactoryBean propertiesFactoryBean = new PropertiesFactoryBean(); propertiesFactoryBean.setLocation(new ClassPathResource("/quartz.properties")); //在quartz.properties中的屬性被讀取并注入后再初始化對象 propertiesFactoryBean.afterPropertiesSet(); //創建SchedulerFactoryBean SchedulerFactoryBean factory = new SchedulerFactoryBean(); factory.setQuartzProperties(propertiesFactoryBean.getObject()); //使用數據源,自定義數據源 factory.setDataSource(this.primaryDataSource); factory.setJobFactory(jobFactory); factory.setWaitForJobsToCompleteOnShutdown(true);//這樣當spring關閉時,會等待所有已經啟動的quartz job結束后spring才能完全shutdown。 factory.setOverwriteExistingJobs(false); factory.setStartupDelay(1); return factory; } /* * 通過SchedulerFactoryBean獲取Scheduler的實例 */ @Bean(name="scheduler") public Scheduler scheduler() throws IOException { return schedulerFactoryBean().getScheduler(); } @Bean public QuartzInitializerListener executorListener() { return new QuartzInitializerListener(); } }
4.創建定時任務服務
@Service public class JobUtil { @Autowired @Qualifier("scheduler") private Scheduler scheduler; /** * 新建一個任務 * */ public String addJob(AppQuartz appQuartz) throws Exception { SimpleDateFormat df = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss"); Date date=df.parse(appQuartz.getStartTime()); if (!CronExpression.isValidExpression(appQuartz.getCronExpression())) { return "Illegal cron expression"; //表達式格式不正確 } JobDetail jobDetail=null; //構建job信息 if("JobOne".equals(appQuartz.getJobGroup())) { jobDetail = JobBuilder.newJob(JobOne.class).withIdentity(appQuartz.getJobName(), appQuartz.getJobGroup()).build(); } if("JobTwo".equals(appQuartz.getJobGroup())) { jobDetail = JobBuilder.newJob(JobTwo.class).withIdentity(appQuartz.getJobName(), appQuartz.getJobGroup()).build(); } //表達式調度構建器(即任務執行的時間,不立即執行) CronScheduleBuilder scheduleBuilder = CronScheduleBuilder.cronSchedule(appQuartz.getCronExpression()).withMisfireHandlingInstructionDoNothing(); //按新的cronExpression表達式構建一個新的trigger CronTrigger trigger = TriggerBuilder.newTrigger().withIdentity(appQuartz.getJobName(), appQuartz.getJobGroup()).startAt(date) .withSchedule(scheduleBuilder).build(); //傳遞參數 if(appQuartz.getInvokeParam()!=null && !"".equals(appQuartz.getInvokeParam())) { trigger.getJobDataMap().put("invokeParam",appQuartz.getInvokeParam()); } scheduler.scheduleJob(jobDetail, trigger); // pauseJob(appQuartz.getJobName(),appQuartz.getJobGroup()); return "success"; } /** * 獲取Job狀態 * @param jobName * @param jobGroup * @return * @throws SchedulerException */ public String getJobState(String jobName, String jobGroup) throws SchedulerException { TriggerKey triggerKey = new TriggerKey(jobName, jobGroup); return scheduler.getTriggerState(triggerKey).name(); } //暫停所有任務 public void pauseAllJob() throws SchedulerException { scheduler.pauseAll(); } //暫停任務 public String pauseJob(String jobName, String jobGroup) throws SchedulerException { JobKey jobKey = new JobKey(jobName, jobGroup); JobDetail jobDetail = scheduler.getJobDetail(jobKey); if (jobDetail == null) { return "fail"; }else { scheduler.pauseJob(jobKey); return "success"; } } //恢復所有任務 public void resumeAllJob() throws SchedulerException { scheduler.resumeAll(); } // 恢復某個任務 public String resumeJob(String jobName, String jobGroup) throws SchedulerException { JobKey jobKey = new JobKey(jobName, jobGroup); JobDetail jobDetail = scheduler.getJobDetail(jobKey); if (jobDetail == null) { return "fail"; }else { scheduler.resumeJob(jobKey); return "success"; } } //刪除某個任務 public String deleteJob(AppQuartz appQuartz) throws SchedulerException { JobKey jobKey = new JobKey(appQuartz.getJobName(), appQuartz.getJobGroup()); JobDetail jobDetail = scheduler.getJobDetail(jobKey); if (jobDetail == null ) { return "jobDetail is null"; }else if(!scheduler.checkExists(jobKey)) { return "jobKey is not exists"; }else { scheduler.deleteJob(jobKey); return "success"; } } //修改任務 public String modifyJob(AppQuartz appQuartz) throws SchedulerException { if (!CronExpression.isValidExpression(appQuartz.getCronExpression())) { return "Illegal cron expression"; } TriggerKey triggerKey = TriggerKey.triggerKey(appQuartz.getJobName(),appQuartz.getJobGroup()); JobKey jobKey = new JobKey(appQuartz.getJobName(),appQuartz.getJobGroup()); if (scheduler.checkExists(jobKey) && scheduler.checkExists(triggerKey)) { CronTrigger trigger = (CronTrigger) scheduler.getTrigger(triggerKey); //表達式調度構建器,不立即執行 CronScheduleBuilder scheduleBuilder = CronScheduleBuilder.cronSchedule(appQuartz.getCronExpression()).withMisfireHandlingInstructionDoNothing(); //按新的cronExpression表達式重新構建trigger trigger = trigger.getTriggerBuilder().withIdentity(triggerKey) .withSchedule(scheduleBuilder).build(); //修改參數 if(!trigger.getJobDataMap().get("invokeParam").equals(appQuartz.getInvokeParam())) { trigger.getJobDataMap().put("invokeParam",appQuartz.getInvokeParam()); } //按新的trigger重新設置job執行 scheduler.rescheduleJob(triggerKey, trigger); return "success"; }else { return "job or trigger not exists"; } } }
@PersistJobDataAfterExecution @DisallowConcurrentExecution @Component public class JonOne implements Job{ @Override public void execute(JobExecutionContext context) throws JobExecutionException{ JobDataMap data=context.getTrigger().getJobDataMap(); String invokeParam =(String) data.get("invokeParam"); //在這里實現業務邏輯 } }
@PersistJobDataAfterExecution @DisallowConcurrentExecution @Component public class JobTwo implements Job{ @Override public void execute(JobExecutionContext context) throws JobExecutionException{ JobDataMap data=context.getTrigger().getJobDataMap(); String invokeParam =(String) data.get("invokeParam"); //在這里實現業務邏輯 } }
說明:每個定時任務都必須有一個分組,名稱和corn表達式,corn表達式也就是定時任務的觸發時間,關于corn表達式格式以及含義可以參考一些網絡資源。每個定時任務都有一個入口類在這里我把類名當成定時任務的分組名稱,例如:只要創建定時任務的分組是JobOne的都會執行JobOne這個任務類里面的邏輯。如果定時任務需要額外的參數可以使用JobDataMap傳遞參數,當然也可以從數據庫中獲取需要的數據。@PersistJobDataAfterExecution和@DisallowConcurrentExecution注解是不讓某個定時任務并發執行,只有等當前任務完成下一個任務才會去執行。
5.封裝定時任務接口
@RestController public class JobController { @Autowired private JobUtil jobUtil; @Autowired private AppQuartzService appQuartzService; //添加一個job @RequestMapping(value="/addJob",method=RequestMethod.POST) public ReturnMsg addjob(@RequestBody AppQuartz appQuartz) throws Exception { appQuartzService.insertAppQuartzSer(appQuartz); result=jobUtil.addJob(appQuartz); } //暫停job @RequestMapping(value="/pauseJob",method=RequestMethod.POST) public ReturnMsg pausejob(@RequestBody Integer[]quartzIds) throws Exception { AppQuartz appQuartz=null; if(quartzIds.length>0){ for(Integer quartzId:quartzIds) { appQuartz=appQuartzService.selectAppQuartzByIdSer(quartzId).get(0); jobUtil.pauseJob(appQuartz.getJobName(), appQuartz.getJobGroup()); } return new ReturnMsg("200","success pauseJob"); }else { return new ReturnMsg("404","fail pauseJob"); } } //恢復job @RequestMapping(value="/resumeJob",method=RequestMethod.POST) public ReturnMsg resumejob(@RequestBody Integer[]quartzIds) throws Exception { AppQuartz appQuartz=null; if(quartzIds.length>0) { for(Integer quartzId:quartzIds) { appQuartz=appQuartzService.selectAppQuartzByIdSer(quartzId).get(0); jobUtil.resumeJob(appQuartz.getJobName(), appQuartz.getJobGroup()); } return new ReturnMsg("200","success resumeJob"); }else { return new ReturnMsg("404","fail resumeJob"); } } //刪除job @RequestMapping(value="/deletJob",method=RequestMethod.POST) public ReturnMsg deletjob(@RequestBody Integer[]quartzIds) throws Exception { AppQuartz appQuartz=null; for(Integer quartzId:quartzIds) { appQuartz=appQuartzService.selectAppQuartzByIdSer(quartzId).get(0); String ret=jobUtil.deleteJob(appQuartz); if("success".equals(ret)) { appQuartzService.deleteAppQuartzByIdSer(quartzId); } } return new ReturnMsg("200","success deleteJob"); } //修改 @RequestMapping(value="/updateJob",method=RequestMethod.POST) public ReturnMsg modifyJob(@RequestBody AppQuartz appQuartz) throws Exception { String ret= jobUtil.modifyJob(appQuartz); if("success".equals(ret)) { appQuartzService.updateAppQuartzSer(appQuartz); return new ReturnMsg("200","success updateJob",ret); }else { return new ReturnMsg("404","fail updateJob",ret); } } //暫停所有 @RequestMapping(value="/pauseAll",method=RequestMethod.GET) public ReturnMsg pauseAllJob() throws Exception { jobUtil.pauseAllJob(); return new ReturnMsg("200","success pauseAll"); } //恢復所有 @RequestMapping(value="/repauseAll",method=RequestMethod.GET) public ReturnMsg repauseAllJob() throws Exception { jobUtil.resumeAllJob(); return new ReturnMsg("200","success repauseAll"); } }
文章版權歸作者所有,未經允許請勿轉載,若此文章存在違規行為,您可以聯系管理員刪除。
轉載請注明本文地址:http://specialneedsforspecialkids.com/yun/77331.html
摘要:而我這里定時任務的觸發是要通過接口的方式來觸發,所以只用實現以下的調度器即可。我這里簡單說下任務的調度器,具體的任務類,觸發器,任務什么時候執行是由它決定的。遇到的坑解決方式這個是因為不兼容的問題,所以使用是不會出現這個錯誤的。 實現定時任務的幾種方式: 1.使用linux的crontab 優點: 1.使用方式很簡單,只要在crontab中寫好 2.隨時可以修改,不需要...
閱讀 1061·2023-04-26 02:02
閱讀 2400·2021-09-26 10:11
閱讀 3552·2019-08-30 13:10
閱讀 3743·2019-08-29 17:12
閱讀 718·2019-08-29 14:20
閱讀 2186·2019-08-28 18:19
閱讀 2229·2019-08-26 13:52
閱讀 954·2019-08-26 13:43