亚洲激情专区-91九色丨porny丨老师-久久久久久久女国产乱让韩-国产精品午夜小视频观看

溫馨提示×

溫馨提示×

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

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

springboot+Quartz實現任務調度的示例代碼

發布時間:2020-09-16 15:52:18 來源:腳本之家 閱讀:149 作者:殷天文 欄目:編程語言

在spring框架中通過 @Schedule 可以實現定時任務,通過該注解 cron 的屬性描述的規則,spring會去調用這個方法。

spring已經簡單粗暴的實現了定時任務,為什么要使用Quartz ?

如果你現在有很多個定時任務,規則不同,例如:

  1. 想每月25號,信用卡自動還款
  2. 想每年4月1日自己給當年暗戀女神發一封匿名賀卡
  3. 想每隔1小時,備份一下自己的愛情動作片 學習筆記到云盤

maven 依賴

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

以下是bootdo開源學習框架的源碼

我并沒有用到全部的字段,思路是先查詢DB,

封裝以下兩個對象

  1. JobDetail 負責存放 job 所需要的數據
  2. Trigger 設置 job 的 key,規則(cron)何時開啟任務等屬性

當觸發條件滿足時,會根據所設置的beanClass 找到該類(必須實現org.quartz.Job), 這時可以取出JobDetail 中的數據,執行具體業務邏輯

@Component
public class WelcomeJob implements Job{
  @Override
  public void execute(JobExecutionContext arg0) throws JobExecutionException {
    //你的業務邏輯
  }
}

表結構

CREATE TABLE `sys_task` (
 `id` bigint(20) NOT NULL AUTO_INCREMENT,
 `cronExpression` varchar(255) DEFAULT NULL COMMENT 'cron表達式',
 `methodName` varchar(255) DEFAULT NULL COMMENT '任務調用的方法名',
 `isConcurrent` varchar(255) DEFAULT NULL COMMENT '任務是否有狀態',
 `description` varchar(255) DEFAULT NULL COMMENT '任務描述',
 `updateBy` varchar(64) DEFAULT NULL COMMENT '更新者',
 `beanClass` varchar(255) DEFAULT NULL COMMENT '任務執行時調用哪個類的方法 包名+類名',
 `createDate` datetime DEFAULT NULL COMMENT '創建時間',
 `jobStatus` varchar(255) DEFAULT NULL COMMENT '任務狀態',
 `jobGroup` varchar(255) DEFAULT NULL COMMENT '任務分組',
 `updateDate` datetime DEFAULT NULL COMMENT '更新時間',
 `createBy` varchar(64) DEFAULT NULL COMMENT '創建者',
 `springBean` varchar(255) DEFAULT NULL COMMENT 'Spring bean',
 `jobName` varchar(255) DEFAULT NULL COMMENT '任務名',
 PRIMARY KEY (`id`)
) ENGINE=InnoDB AUTO_INCREMENT=3 DEFAULT CHARSET=utf8 ROW_FORMAT=COMPACT;

配置類

import java.io.IOException;
import java.util.Properties;
import org.quartz.Scheduler;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.config.PropertiesFactoryBean;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.core.io.ClassPathResource;
import org.springframework.scheduling.quartz.SchedulerFactoryBean;
import com.txgl.common.quartz.factory.JobFactory;
@Configuration
public class QuartzConfigration {

  @Autowired
  JobFactory jobFactory;

  @Bean
  public SchedulerFactoryBean schedulerFactoryBean() {
    SchedulerFactoryBean schedulerFactoryBean = new SchedulerFactoryBean();
    try {
      schedulerFactoryBean.setOverwriteExistingJobs(true);
      schedulerFactoryBean.setQuartzProperties(quartzProperties());
      schedulerFactoryBean.setJobFactory(jobFactory);
    } catch (IOException e) {
      e.printStackTrace();
    }
    return schedulerFactoryBean;
  }

  // 指定quartz.properties
  @Bean
  public Properties quartzProperties() throws IOException {
    PropertiesFactoryBean propertiesFactoryBean = new PropertiesFactoryBean();
    propertiesFactoryBean.setLocation(new ClassPathResource("/config/quartz.properties"));
    propertiesFactoryBean.afterPropertiesSet();
    return propertiesFactoryBean.getObject();
  }

  // 創建schedule
  @Bean(name = "scheduler")
  public Scheduler scheduler() {
    return schedulerFactoryBean().getScheduler();
  }
}

QuartzManager的代碼是關鍵,通過注入Scheduler 對任務進行操作

import java.util.ArrayList;
import java.util.List;
import java.util.Set;
import org.apache.log4j.Logger;
import org.quartz.CronScheduleBuilder;
import org.quartz.CronTrigger;
import org.quartz.DateBuilder;
import org.quartz.DateBuilder.IntervalUnit;
import org.quartz.Job;
import org.quartz.JobBuilder;
import org.quartz.JobDetail;
import org.quartz.JobExecutionContext;
import org.quartz.JobKey;
import org.quartz.Scheduler;
import org.quartz.SchedulerException;
import org.quartz.Trigger;
import org.quartz.TriggerBuilder;
import org.quartz.TriggerKey;
import org.quartz.impl.matchers.GroupMatcher;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Qualifier;
import org.springframework.scheduling.quartz.SchedulerFactoryBean;
import org.springframework.stereotype.Service;
import org.springframework.web.context.support.SpringBeanAutowiringSupport;
import com.bootdo.common.domain.ScheduleJob;
import com.bootdo.common.quartz.factory.*;
import com.bootdo.common.utils.SpringContextHolder;;

/**
 * 
 * 
 * @title: QuartzManager.java
 * @description: 計劃任務管理
 *
 */
@Service
public class QuartzManager {
  public final Logger log = Logger.getLogger(this.getClass());
  // private SchedulerFactoryBean schedulerFactoryBean
  // =SpringContextHolder.getBean(SchedulerFactoryBean.class);
  // @Autowired
  // @Qualifier("schedulerFactoryBean")
  // private SchedulerFactoryBean schedulerFactoryBean;
  @Autowired
  private Scheduler scheduler;

  /**
   * 添加任務
   * 
   * @param scheduleJob
   * @throws SchedulerException
   */
  
  public void addJob(ScheduleJob job) {
    try {
      // 創建jobDetail實例,綁定Job實現類
      // 指明job的名稱,所在組的名稱,以及綁定job類
      Class<? extends Job> jobClass = (Class<? extends Job>) (Class.forName(job.getBeanClass()).newInstance()
          .getClass());
      JobDetail jobDetail = JobBuilder.newJob(jobClass).withIdentity(job.getJobName(), job.getJobGroup())// 任務名稱和組構成任務key
          .build();
      // 定義調度觸發規則
      // 使用cornTrigger規則
      Trigger trigger = TriggerBuilder.newTrigger().withIdentity(job.getJobName(), job.getJobGroup())// 觸發器key
          .startAt(DateBuilder.futureDate(1, IntervalUnit.SECOND))
          .withSchedule(CronScheduleBuilder.cronSchedule(job.getCronExpression())).startNow().build();
      // 把作業和觸發器注冊到任務調度中
      scheduler.scheduleJob(jobDetail, trigger);
      // 啟動
      if (!scheduler.isShutdown()) {
        scheduler.start();
      }
    } catch (Exception e) {
      e.printStackTrace();
    }
  }
// public void addJob(ScheduleJob job) throws SchedulerException {
//   if (job == null || !ScheduleJob.STATUS_RUNNING.equals(job.getJobStatus())) {
//     return;
//   }
//
//   TriggerKey triggerKey = TriggerKey.triggerKey(job.getJobName(), job.getJobGroup());
//
//   CronTrigger trigger = (CronTrigger) scheduler.getTrigger(triggerKey);
//
//   // 不存在,創建一個
//
//   if (null == trigger) {
//     Class<? extends Job> clazz = ScheduleJob.CONCURRENT_IS.equals(job.getIsConcurrent())
//         ? QuartzJobFactory.class
//         : QuartzJobFactoryDisallowConcurrentExecution.class;
//
//     JobDetail jobDetail = JobBuilder.newJob(clazz).withIdentity(job.getJobName(), job.getJobGroup()).build();
//
//     jobDetail.getJobDataMap().put("scheduleJob", job);
//
//     CronScheduleBuilder scheduleBuilder = CronScheduleBuilder.cronSchedule(job.getCronExpression());
//
//     trigger = TriggerBuilder.newTrigger().withIdentity(job.getJobName(), job.getJobGroup())
//         .withSchedule(scheduleBuilder).build();
//
//     scheduler.scheduleJob(jobDetail, trigger);
//   } else {
//     // Trigger已存在,那么更新相應的定時設置
//
//     CronScheduleBuilder scheduleBuilder = CronScheduleBuilder.cronSchedule(job.getCronExpression());
//
//     // 按新的cronExpression表達式重新構建trigger
//
//     trigger = trigger.getTriggerBuilder().withIdentity(triggerKey).withSchedule(scheduleBuilder).build();
//
//     // 按新的trigger重新設置job執行
//
//     scheduler.rescheduleJob(triggerKey, trigger);
//   }
// }

  /**
   * 獲取所有計劃中的任務列表
   * 
   * @return
   * @throws SchedulerException
   */
  public List<ScheduleJob> getAllJob() throws SchedulerException {
    GroupMatcher<JobKey> matcher = GroupMatcher.anyJobGroup();
    Set<JobKey> jobKeys = scheduler.getJobKeys(matcher);
    List<ScheduleJob> jobList = new ArrayList<ScheduleJob>();
    for (JobKey jobKey : jobKeys) {
      List<? extends Trigger> triggers = scheduler.getTriggersOfJob(jobKey);
      for (Trigger trigger : triggers) {
        ScheduleJob job = new ScheduleJob();
        job.setJobName(jobKey.getName());
        job.setJobGroup(jobKey.getGroup());
        job.setDescription("觸發器:" + trigger.getKey());
        Trigger.TriggerState triggerState = scheduler.getTriggerState(trigger.getKey());
        job.setJobStatus(triggerState.name());
        if (trigger instanceof CronTrigger) {
          CronTrigger cronTrigger = (CronTrigger) trigger;
          String cronExpression = cronTrigger.getCronExpression();
          job.setCronExpression(cronExpression);
        }
        jobList.add(job);
      }
    }
    return jobList;
  }

  /**
   * 所有正在運行的job
   * 
   * @return
   * @throws SchedulerException
   */
  public List<ScheduleJob> getRunningJob() throws SchedulerException {
    List<JobExecutionContext> executingJobs = scheduler.getCurrentlyExecutingJobs();
    List<ScheduleJob> jobList = new ArrayList<ScheduleJob>(executingJobs.size());
    for (JobExecutionContext executingJob : executingJobs) {
      ScheduleJob job = new ScheduleJob();
      JobDetail jobDetail = executingJob.getJobDetail();
      JobKey jobKey = jobDetail.getKey();
      Trigger trigger = executingJob.getTrigger();
      job.setJobName(jobKey.getName());
      job.setJobGroup(jobKey.getGroup());
      job.setDescription("觸發器:" + trigger.getKey());
      Trigger.TriggerState triggerState = scheduler.getTriggerState(trigger.getKey());
      job.setJobStatus(triggerState.name());
      if (trigger instanceof CronTrigger) {
        CronTrigger cronTrigger = (CronTrigger) trigger;
        String cronExpression = cronTrigger.getCronExpression();
        job.setCronExpression(cronExpression);
      }
      jobList.add(job);
    }
    return jobList;
  }

  /**
   * 暫停一個job
   * 
   * @param scheduleJob
   * @throws SchedulerException
   */
  public void pauseJob(ScheduleJob scheduleJob) throws SchedulerException {
    JobKey jobKey = JobKey.jobKey(scheduleJob.getJobName(), scheduleJob.getJobGroup());
    scheduler.pauseJob(jobKey);
  }

  /**
   * 恢復一個job
   * 
   * @param scheduleJob
   * @throws SchedulerException
   */
  public void resumeJob(ScheduleJob scheduleJob) throws SchedulerException {
    JobKey jobKey = JobKey.jobKey(scheduleJob.getJobName(), scheduleJob.getJobGroup());
    scheduler.resumeJob(jobKey);
  }

  /**
   * 刪除一個job
   * 
   * @param scheduleJob
   * @throws SchedulerException
   */
  public void deleteJob(ScheduleJob scheduleJob) throws SchedulerException {
    JobKey jobKey = JobKey.jobKey(scheduleJob.getJobName(), scheduleJob.getJobGroup());
    scheduler.deleteJob(jobKey);

  }

  /**
   * 立即執行job
   * 
   * @param scheduleJob
   * @throws SchedulerException
   */
  public void runAJobNow(ScheduleJob scheduleJob) throws SchedulerException {
    JobKey jobKey = JobKey.jobKey(scheduleJob.getJobName(), scheduleJob.getJobGroup());
    scheduler.triggerJob(jobKey);
  }

  /**
   * 更新job時間表達式
   * 
   * @param scheduleJob
   * @throws SchedulerException
   */
  public void updateJobCron(ScheduleJob scheduleJob) throws SchedulerException {

    TriggerKey triggerKey = TriggerKey.triggerKey(scheduleJob.getJobName(), scheduleJob.getJobGroup());

    CronTrigger trigger = (CronTrigger) scheduler.getTrigger(triggerKey);

    CronScheduleBuilder scheduleBuilder = CronScheduleBuilder.cronSchedule(scheduleJob.getCronExpression());

    trigger = trigger.getTriggerBuilder().withIdentity(triggerKey).withSchedule(scheduleBuilder).build();

    scheduler.rescheduleJob(triggerKey, trigger);
  }
}

service實現

import com.bootdo.common.config.Constant;
import com.bootdo.common.dao.TaskDao;
import com.bootdo.common.domain.ScheduleJob;
import com.bootdo.common.domain.TaskDO;
import com.bootdo.common.quartz.utils.QuartzManager;
import com.bootdo.common.service.JobService;
import com.bootdo.common.utils.ScheduleJobUtils;
import org.quartz.SchedulerException;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

@Service
public class JobServiceImpl implements JobService {

  @Autowired
  private TaskDao taskScheduleJobMapper;

  @Autowired
  QuartzManager quartzManager;

  @Override
  public TaskDO get(Long id) {
    return taskScheduleJobMapper.get(id);
  }

  @Override
  public List<TaskDO> list(Map<String, Object> map) {
    return taskScheduleJobMapper.list(map);
  }

  @Override
  public int count(Map<String, Object> map) {
    return taskScheduleJobMapper.count(map);
  }

  @Override
  public int save(TaskDO taskScheduleJob) {
    return taskScheduleJobMapper.save(taskScheduleJob);
  }

  @Override
  public int update(TaskDO taskScheduleJob) {
    return taskScheduleJobMapper.update(taskScheduleJob);
  }

  @Override
  public int remove(Long id) {
    try {
      TaskDO scheduleJob = get(id);
      quartzManager.deleteJob(ScheduleJobUtils.entityToData(scheduleJob));
      return taskScheduleJobMapper.remove(id);
    } catch (SchedulerException e) {
      e.printStackTrace();
      return 0;
    }

  }

  @Override
  public int batchRemove(Long[] ids) {
    for (Long id : ids) {
      try {
        TaskDO scheduleJob = get(id);
        quartzManager.deleteJob(ScheduleJobUtils.entityToData(scheduleJob));
      } catch (SchedulerException e) {
        e.printStackTrace();
        return 0;
      }
    }
    return taskScheduleJobMapper.batchRemove(ids);
  }

  @Override
  public void initSchedule() throws SchedulerException {
    // 這里獲取任務信息數據
    List<TaskDO> jobList = taskScheduleJobMapper.list(new HashMap<String, Object>(16));
    for (TaskDO scheduleJob : jobList) {
      if ("1".equals(scheduleJob.getJobStatus())) {
        ScheduleJob job = ScheduleJobUtils.entityToData(scheduleJob);
        quartzManager.addJob(job);
      }

    }
  }

  @Override
  public void changeStatus(Long jobId, String cmd) throws SchedulerException {
    TaskDO scheduleJob = get(jobId);
    if (scheduleJob == null) {
      return;
    }
    if (Constant.STATUS_RUNNING_STOP.equals(cmd)) {
      quartzManager.deleteJob(ScheduleJobUtils.entityToData(scheduleJob));
      scheduleJob.setJobStatus(ScheduleJob.STATUS_NOT_RUNNING);
    } else {
      if (!Constant.STATUS_RUNNING_START.equals(cmd)) {
      } else {
        scheduleJob.setJobStatus(ScheduleJob.STATUS_RUNNING);
        quartzManager.addJob(ScheduleJobUtils.entityToData(scheduleJob));
      }
    }
    update(scheduleJob);
  }

  @Override
  public void updateCron(Long jobId) throws SchedulerException {
    TaskDO scheduleJob = get(jobId);
    if (scheduleJob == null) {
      return;
    }
    if (ScheduleJob.STATUS_RUNNING.equals(scheduleJob.getJobStatus())) {
      quartzManager.updateJobCron(ScheduleJobUtils.entityToData(scheduleJob));
    }
    update(scheduleJob);
  }
}

啟動一個監聽去初始化Quartz

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.boot.CommandLineRunner;
import org.springframework.core.annotation.Order;
import org.springframework.stereotype.Component;
import com.bootdo.common.quartz.utils.QuartzManager;
import com.bootdo.common.service.JobService;
@Component
@Order(value = 1)
public class ScheduleJobInitListener implements CommandLineRunner {

  @Autowired
  JobService scheduleJobService;

  @Autowired
  QuartzManager quartzManager;

  @Override
  public void run(String... arg0) throws Exception {
    try {
      scheduleJobService.initSchedule();
    } catch (Exception e) {
      e.printStackTrace();
    }
  }
}

以上就是本文的全部內容,希望對大家的學習有所幫助,也希望大家多多支持億速云。

向AI問一下細節

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

AI

淮北市| 杂多县| 遂溪县| 榕江县| 工布江达县| 邵阳市| 龙井市| 行唐县| 都匀市| 察哈| 鹤岗市| 琼结县| 葫芦岛市| 义马市| 广元市| 崇信县| 庆安县| 太和县| 九龙坡区| 陆川县| 靖安县| 孟津县| 元谋县| 宁南县| 荥阳市| 安义县| 长白| 剑阁县| 嘉禾县| 五常市| 基隆市| 花垣县| 长子县| 永州市| 宁强县| 禹城市| 景洪市| 和顺县| 石台县| 东兰县| 拉萨市|