中文字幕av专区_日韩电影在线播放_精品国产精品久久一区免费式_av在线免费观看网站

溫馨提示×

溫馨提示×

您好,登錄后才能下訂單哦!

密碼登錄×
登錄注冊×
其他方式登錄
點擊 登錄注冊 即表示同意《億速云用戶服務條款》

淺談SpringBoot集成Quartz動態定時任務

發布時間:2020-10-21 01:49:23 來源:腳本之家 閱讀:189 作者:yvan1115 欄目:編程語言

SpringBoot自帶schedule

沿用的springboot少xml配置的優良傳統,本身支持表達式等多種定時任務
注意在程序啟動的時候加上@EnableScheduling

@Scheduled(cron="0/5 * * * * ?")
 public void job(){
  System.out.println("每五秒執行一次");
 }

為什么要使用Quartz

多任務情況下,quartz更容易管理,可以實現動態配置
執行時間表達式:

淺談SpringBoot集成Quartz動態定時任務

表達式示例:

淺談SpringBoot集成Quartz動態定時任務

集成Quartz

如何搭建springboot就不再細說,官網和網上的教程很多。

maven依賴

<dependency>
   <groupId>org.quartz-scheduler</groupId>
   <artifactId>quartz</artifactId>
   <version>2.2.1</version>
  </dependency>

 測試Job類
SchedulerQuartzJob1和SchedulerQuartzJob2代碼差不多就不一一列出

package com.yvan.quartz.job;

import org.quartz.Job;
import org.quartz.JobExecutionContext;
import org.quartz.JobExecutionException;
/**
 * 實現Job接口
 * @author yvan
 *
 */
public class SchedulerQuartzJob1 implements Job{
 private void before(){
  System.out.println("任務開始執行");
 }

 @Override
 public void execute(JobExecutionContext arg0) throws JobExecutionException {
  before();
  System.out.println("開始:"+System.currentTimeMillis());
  // TODO 業務
  System.out.println("結束:"+System.currentTimeMillis());
  after();
 }

 private void after(){
  System.out.println("任務開始執行");
 }

}

任務調用處理
將其拆分成兩個部分

實例化Job,將任務觸發器加入任務調度中

 private void startJob1(Scheduler scheduler) throws SchedulerException {
  // 通過JobBuilder構建JobDetail實例,JobDetail規定只能是實現Job接口的實例
  // JobDetail 是具體Job實例
  JobDetail jobDetail = JobBuilder.newJob(SchedulerQuartzJob1.class).withIdentity("job1", "group1").build();
  // 基于表達式構建觸發器
  CronScheduleBuilder cronScheduleBuilder = CronScheduleBuilder.cronSchedule("0/5 * * * * ?");
  // CronTrigger表達式觸發器 繼承于Trigger
  // TriggerBuilder 用于構建觸發器實例
  CronTrigger cronTrigger = TriggerBuilder.newTrigger().withIdentity("job1", "group1")
    .withSchedule(cronScheduleBuilder).build();
  scheduler.scheduleJob(jobDetail, cronTrigger);
 }

 private void startJob2(Scheduler scheduler) throws SchedulerException {
  JobDetail jobDetail = JobBuilder.newJob(SchedulerQuartzJob2.class).withIdentity("job2", "group2").build();
  CronScheduleBuilder cronScheduleBuilder = CronScheduleBuilder.cronSchedule("0 0/5 * * * ?");
  CronTrigger cronTrigger = TriggerBuilder.newTrigger().withIdentity("job2", "group2")
    .withSchedule(cronScheduleBuilder).build();
  scheduler.scheduleJob(jobDetail, cronTrigger);
 }

對外提供關于動態管理任務的方法

 /**
  * 開始執行所有任務
  * 
  * @throws SchedulerException
  */
 public void startJob() throws SchedulerException {
  startJob1(scheduler);
  startJob2(scheduler);
  scheduler.start();
 }

 /**
  * 獲取Job信息
  * 
  * @param name
  * @param group
  * @return
  * @throws SchedulerException
  */
 public String getJobInfo(String name, String group) throws SchedulerException {
  TriggerKey triggerKey = new TriggerKey(name, group);
  CronTrigger cronTrigger = (CronTrigger) scheduler.getTrigger(triggerKey);
  return String.format("time:%s,state:%s", cronTrigger.getCronExpression(),
    scheduler.getTriggerState(triggerKey).name());
 }

 /**
  * 修改某個任務的執行時間
  * 
  * @param name
  * @param group
  * @param time
  * @return
  * @throws SchedulerException
  */
 public boolean modifyJob(String name, String group, String time) throws SchedulerException {
  Date date = null;
  TriggerKey triggerKey = new TriggerKey(name, group);
  CronTrigger cronTrigger = (CronTrigger) scheduler.getTrigger(triggerKey);
  String oldTime = cronTrigger.getCronExpression();
  if (!oldTime.equalsIgnoreCase(time)) {
   CronScheduleBuilder cronScheduleBuilder = CronScheduleBuilder.cronSchedule(time);
   CronTrigger trigger = TriggerBuilder.newTrigger().withIdentity(name, group)
     .withSchedule(cronScheduleBuilder).build();
   date = scheduler.rescheduleJob(triggerKey, trigger);
  }
  return date != null;
 }

 /**
  * 暫停所有任務
  * 
  * @throws SchedulerException
  */
 public void pauseAllJob() throws SchedulerException {
  scheduler.pauseAll();
 }

 /**
  * 暫停某個任務
  * 
  * @param name
  * @param group
  * @throws SchedulerException
  */
 public void pauseJob(String name, String group) throws SchedulerException {
  JobKey jobKey = new JobKey(name, group);
  JobDetail jobDetail = scheduler.getJobDetail(jobKey);
  if (jobDetail == null)
   return;
  scheduler.pauseJob(jobKey);
 }

 /**
  * 恢復所有任務
  * 
  * @throws SchedulerException
  */
 public void resumeAllJob() throws SchedulerException {
  scheduler.resumeAll();
 }

 /**
  * 恢復某個任務
  * 
  * @param name
  * @param group
  * @throws SchedulerException
  */
 public void resumeJob(String name, String group) throws SchedulerException {
  JobKey jobKey = new JobKey(name, group);
  JobDetail jobDetail = scheduler.getJobDetail(jobKey);
  if (jobDetail == null)
   return;
  scheduler.resumeJob(jobKey);
 }

 /**
  * 刪除某個任務
  * 
  * @param name
  * @param group
  * @throws SchedulerException
  */
 public void deleteJob(String name, String group) throws SchedulerException {
  JobKey jobKey = new JobKey(name, group);
  JobDetail jobDetail = scheduler.getJobDetail(jobKey);
  if (jobDetail == null)
   return;
  scheduler.deleteJob(jobKey);
 }

完整代碼

package com.yvan.quartz;

import java.util.Date;

import org.quartz.CronScheduleBuilder;
import org.quartz.CronTrigger;
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.TriggerKey;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.context.annotation.Configuration;

import com.yvan.quartz.job.SchedulerQuartzJob1;
import com.yvan.quartz.job.SchedulerQuartzJob2;
/**
 * 任務調度處理
 * @author yvan
 *
 */
@Configuration
public class QuartzScheduler {
 // 任務調度
 @Autowired
 private Scheduler scheduler;

 /**
  * 開始執行所有任務
  * 
  * @throws SchedulerException
  */
 public void startJob() throws SchedulerException {
  startJob1(scheduler);
  startJob2(scheduler);
  scheduler.start();
 }

 /**
  * 獲取Job信息
  * 
  * @param name
  * @param group
  * @return
  * @throws SchedulerException
  */
 public String getJobInfo(String name, String group) throws SchedulerException {
  TriggerKey triggerKey = new TriggerKey(name, group);
  CronTrigger cronTrigger = (CronTrigger) scheduler.getTrigger(triggerKey);
  return String.format("time:%s,state:%s", cronTrigger.getCronExpression(),
    scheduler.getTriggerState(triggerKey).name());
 }

 /**
  * 修改某個任務的執行時間
  * 
  * @param name
  * @param group
  * @param time
  * @return
  * @throws SchedulerException
  */
 public boolean modifyJob(String name, String group, String time) throws SchedulerException {
  Date date = null;
  TriggerKey triggerKey = new TriggerKey(name, group);
  CronTrigger cronTrigger = (CronTrigger) scheduler.getTrigger(triggerKey);
  String oldTime = cronTrigger.getCronExpression();
  if (!oldTime.equalsIgnoreCase(time)) {
   CronScheduleBuilder cronScheduleBuilder = CronScheduleBuilder.cronSchedule(time);
   CronTrigger trigger = TriggerBuilder.newTrigger().withIdentity(name, group)
     .withSchedule(cronScheduleBuilder).build();
   date = scheduler.rescheduleJob(triggerKey, trigger);
  }
  return date != null;
 }

 /**
  * 暫停所有任務
  * 
  * @throws SchedulerException
  */
 public void pauseAllJob() throws SchedulerException {
  scheduler.pauseAll();
 }

 /**
  * 暫停某個任務
  * 
  * @param name
  * @param group
  * @throws SchedulerException
  */
 public void pauseJob(String name, String group) throws SchedulerException {
  JobKey jobKey = new JobKey(name, group);
  JobDetail jobDetail = scheduler.getJobDetail(jobKey);
  if (jobDetail == null)
   return;
  scheduler.pauseJob(jobKey);
 }

 /**
  * 恢復所有任務
  * 
  * @throws SchedulerException
  */
 public void resumeAllJob() throws SchedulerException {
  scheduler.resumeAll();
 }

 /**
  * 恢復某個任務
  * 
  * @param name
  * @param group
  * @throws SchedulerException
  */
 public void resumeJob(String name, String group) throws SchedulerException {
  JobKey jobKey = new JobKey(name, group);
  JobDetail jobDetail = scheduler.getJobDetail(jobKey);
  if (jobDetail == null)
   return;
  scheduler.resumeJob(jobKey);
 }

 /**
  * 刪除某個任務
  * 
  * @param name
  * @param group
  * @throws SchedulerException
  */
 public void deleteJob(String name, String group) throws SchedulerException {
  JobKey jobKey = new JobKey(name, group);
  JobDetail jobDetail = scheduler.getJobDetail(jobKey);
  if (jobDetail == null)
   return;
  scheduler.deleteJob(jobKey);
 }

 private void startJob1(Scheduler scheduler) throws SchedulerException {
  // 通過JobBuilder構建JobDetail實例,JobDetail規定只能是實現Job接口的實例
  // JobDetail 是具體Job實例
  JobDetail jobDetail = JobBuilder.newJob(SchedulerQuartzJob1.class).withIdentity("job1", "group1").build();
  // 基于表達式構建觸發器
  CronScheduleBuilder cronScheduleBuilder = CronScheduleBuilder.cronSchedule("0/5 * * * * ?");
  // CronTrigger表達式觸發器 繼承于Trigger
  // TriggerBuilder 用于構建觸發器實例
  CronTrigger cronTrigger = TriggerBuilder.newTrigger().withIdentity("job1", "group1")
    .withSchedule(cronScheduleBuilder).build();
  scheduler.scheduleJob(jobDetail, cronTrigger);
 }

 private void startJob2(Scheduler scheduler) throws SchedulerException {
  JobDetail jobDetail = JobBuilder.newJob(SchedulerQuartzJob2.class).withIdentity("job2", "group2").build();
  CronScheduleBuilder cronScheduleBuilder = CronScheduleBuilder.cronSchedule("0 0/5 * * * ?");
  CronTrigger cronTrigger = TriggerBuilder.newTrigger().withIdentity("job2", "group2")
    .withSchedule(cronScheduleBuilder).build();
  scheduler.scheduleJob(jobDetail, cronTrigger);
 }
}

Scheduler 注入
這里采用監聽spring容器加載完畢后事件,啟動任務調用
將Scheduler交給spring初始化管理

package com.yvan.quartz;

import org.quartz.Scheduler;
import org.quartz.SchedulerException;
import org.quartz.SchedulerFactory;
import org.quartz.impl.StdSchedulerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.context.ApplicationListener;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.context.event.ContextRefreshedEvent;

@Configuration
public class ApplicationStartQuartzJobListener implements ApplicationListener<ContextRefreshedEvent>{
 @Autowired
 private QuartzScheduler quartzScheduler;

 /**
  * 初始啟動quartz
  */
 @Override
 public void onApplicationEvent(ContextRefreshedEvent event) {
  try {
   quartzScheduler.startJob();
   System.out.println("任務已經啟動...");
  } catch (SchedulerException e) {
   e.printStackTrace();
  }
 }

 /**
  * 初始注入scheduler
  * @return
  * @throws SchedulerException
  */
 @Bean
 public Scheduler scheduler() throws SchedulerException{
  SchedulerFactory schedulerFactoryBean = new StdSchedulerFactory();
  return schedulerFactoryBean.getScheduler(); 
 }

}

封裝API
這里封裝的API主要是為了方便動態管理執行任務,當然依賴這些接口也可以做一個界面來更直觀的操作管理任務,這個就不再贅述。

package com.yvan.controller.quartzApi;

import org.quartz.SchedulerException;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;

import com.yvan.quartz.QuartzScheduler;

/**
 * 這里并沒有采用restful風格 只是簡單封裝了一下api
 * 
 * @author yvan
 *
 */
@RestController
@RequestMapping("/quartz")
public class QuartzApiController {
 @Autowired
 private QuartzScheduler quartzScheduler;

 @RequestMapping("/start")
 public void startQuartzJob() {
  try {
   quartzScheduler.startJob();
  } catch (SchedulerException e) {
   e.printStackTrace();
  }
 }

 @RequestMapping("/info")
 public String getQuartzJob(String name, String group) {
  String info = null;
  try {
   info = quartzScheduler.getJobInfo(name, group);
  } catch (SchedulerException e) {
   e.printStackTrace();
  }
  return info;
 }

 @RequestMapping("/modify")
 public boolean modifyQuartzJob(String name, String group, String time) {
  boolean flag = true;
  try {
   flag = quartzScheduler.modifyJob(name, group, time);
  } catch (SchedulerException e) {
   e.printStackTrace();
  }
  return flag;
 }

 @RequestMapping(value = "/pause")
 public void pauseQuartzJob(String name, String group) {
  try {
   quartzScheduler.pauseJob(name, group);
  } catch (SchedulerException e) {
   e.printStackTrace();
  }
 }

 @RequestMapping(value = "/pauseAll")
 public void pauseAllQuartzJob() {
  try {
   quartzScheduler.pauseAllJob();
  } catch (SchedulerException e) {
   e.printStackTrace();
  }
 }

 @RequestMapping(value = "/delete")
 public void deleteJob(String name, String group) {
  try {
   quartzScheduler.deleteJob(name, group);
  } catch (SchedulerException e) {
   e.printStackTrace();
  }
 }

}

運行結果

任務已經啟動...
18-03-02 14:39:46,879  INFO TomcatEmbeddedServletContainer:201 - Tomcat started on port(s): 8080 (http)
-03-02 14:39:46,883  INFO Start:57 - Started Start in 3.18 seconds (JVM running for 3.47)
任務開始執行
開始:1519972790003
結束:1519972790003
任務開始執行
任務開始執行
開始:1519972795000
結束:1519972795000
任務開始執行

以上所述是小編給大家介紹的SpringBoot集成Quartz動態定時任務詳解整合,希望對大家有所幫助,如果大家有任何疑問請給我留言,小編會及時回復大家的。在此也非常感謝大家對億速云網站的支持!

向AI問一下細節

免責聲明:本站發布的內容(圖片、視頻和文字)以原創、轉載和分享為主,文章觀點不代表本網站立場,如果涉及侵權請聯系站長郵箱:is@yisu.com進行舉報,并提供相關證據,一經查實,將立刻刪除涉嫌侵權內容。

AI

靖远县| 中牟县| 安乡县| 大荔县| 治多县| 平陆县| 黄龙县| 兰州市| 三门峡市| 南皮县| 江西省| 潼关县| 密山市| 秭归县| 绵竹市| 鲁山县| 昌乐县| 琼海市| 湘阴县| 嵊泗县| 容城县| 根河市| 玉龙| 北流市| 淄博市| 牡丹江市| 七台河市| 平罗县| 东阿县| 迁安市| 九龙城区| 眉山市| 兴城市| 梁河县| 五指山市| 济南市| 长阳| 淮南市| 双桥区| 曲阳县| 邮箱|