springboot動態定時任務的實現方法示例

1、maven引入quartz包

<!-- https://mvnrepository.com/artifact/org.quartz-scheduler/quartz -->
<dependency>
 <groupId>org.quartz-scheduler</groupId>
 <artifactId>quartz</artifactId>
 <version>2.3.2</version>
</dependency>

2、創建定時任務工廠類

/**
 * 定時任務工廠類
 */
@Component
public class JobFactory extends SpringBeanJobFactory implements ApplicationContextAware {

 private transient AutowireCapableBeanFactory beanFactory;

 @Override
 protected Object createJobInstance(TriggerFiredBundle bundle) throws Exception {
 final Object jobInstance = super.createJobInstance(bundle);
 beanFactory.autowireBean(jobInstance);
 return jobInstance;
 }

 @Override
 public void setApplicationContext(ApplicationContext applicationContext) throws BeansException {
 this.beanFactory = applicationContext.getAutowireCapableBeanFactory();
 }

}

3、創建定時任務抽象類

public abstract class AbstractTask implements Job {

 private Logger logger = LoggerFactory.getLogger(AbstractTask.class);

 protected abstract void executeInternal(JobExecutionContext context) throws Exception;

 /**
 * 定時任務標識
 */
 private String key;

 /**
 * 數據庫裡配置的主鍵id
 */
 private Long dataBaseId;

 @Override
 public void execute(JobExecutionContext context) {
 try {
  executeInternal(context);
 } catch (Exception e) {
  logger.error(e.getMessage(), e);
  logger.error("job execute failed!");
 }
 }

 public String getKey() {
 return key;
 }

 public void setKey(String key) {
 this.key = key;
 }

 public Long getDataBaseId() {
 return dataBaseId;
 }

 public void setDataBaseId(Long dataBaseId) {
 this.dataBaseId = dataBaseId;
 }
}

4、創建定時任務業務實現類

這裡可以寫你的業務代碼,實現具體的業務邏輯。

@Component("JobTask")
public class JobTask extends AbstractTask {

 @Override
 protected void executeInternal(JobExecutionContext context) {
 System.out.println("key = " + this.getKey());
 System.out.println("dataBaseId = " + this.getDataBaseId());
 }

}

5、創建定時任務管理器

包括項目啟動時添加定時任務,手動添加定時任務,更新定時任務,刪除定時任務方法。

/**
 * 定時任務管理容器 component (單例模式)
 */
@Component
@Scope("singleton")
public class JobQuartzManager implements ApplicationContextAware {

 /**
 * 創建新的scheduler
 */
 private static SchedulerFactory schedulerFactory = new StdSchedulerFactory();

 private Scheduler scheduler;

 /**
 * 定義組名稱,不同的組用於區分任務
 */
 private static final String JOB_GROUP_NAME = "JOB_GROUP_NAME";

 private static final String TRIGGER_GROUP_NAME = "TRIGGER_GROUP_NAME";

 /**
 * 日志
 */
 private Logger logger = LoggerFactory.getLogger(JobQuartzManager.class);

 private ApplicationContext applicationContext;

 @Autowired
 private JobFactory jobFactory;

 public void start() {
 //啟動定時任務(初始化)
 try {
  this.scheduler = schedulerFactory.getScheduler();
  scheduler.setJobFactory(jobFactory); //設置定時任務工廠模式
  //項目啟動時默認給spring容器添加動態的定時任務
  this.addJob("job" + 100L, 100L, JobTask.class, "0/2 * * * * ?");
 } catch (SchedulerException e) {
  logger.error(e.getMessage(), e);
  throw new RuntimeException("init Scheduler failed");
 }
 }

 public boolean addJob(String jobName, Long dataBaseId, Class jobClass, String cronExp) {
 boolean result = false;
 if (!CronExpression.isValidExpression(cronExp)) {
  logger.error("Illegal cron expression format({})", cronExp);
  return result;
 }
 try {
  JobDetail jobDetail = JobBuilder.newJob().withIdentity(new JobKey(jobName, JOB_GROUP_NAME))
   .ofType((Class<AbstractTask>) Class.forName(jobClass.getName()))
   .build();
  //創建完jobDetail之後,使用語句傳參數值,方便定時任務內部識別它是什麼標識
  JobDataMap jobDataMap = jobDetail.getJobDataMap();
  jobDataMap.put("key", jobName);
  jobDataMap.put("dataBaseId", dataBaseId);
  Trigger trigger = TriggerBuilder.newTrigger()
   .forJob(jobDetail)
   .withSchedule(CronScheduleBuilder.cronSchedule(cronExp))
   .withIdentity(new TriggerKey(jobName, TRIGGER_GROUP_NAME))
   .build();
  scheduler.scheduleJob(jobDetail, trigger);
  scheduler.start();
  result = true;
 } catch (Exception e) {
  logger.error(e.getMessage(), e);
  logger.error("QuartzManager add job failed");
 }
 return result;
 }

 public boolean updateJob(String jobName, String cronExp) {
 boolean result = false;
 if (!CronExpression.isValidExpression(cronExp)) {
  logger.error("Illegal cron expression format({})", cronExp);
  return result;
 }
 JobKey jobKey = new JobKey(jobName, JOB_GROUP_NAME);
 TriggerKey triggerKey = new TriggerKey(jobName, TRIGGER_GROUP_NAME);
 try {
  if (scheduler.checkExists(jobKey) && scheduler.checkExists(triggerKey)) {
  JobDetail jobDetail = scheduler.getJobDetail(jobKey);
  Trigger newTrigger = TriggerBuilder.newTrigger()
   .forJob(jobDetail)
   .withSchedule(CronScheduleBuilder.cronSchedule(cronExp))
   .withIdentity(new TriggerKey(jobName, TRIGGER_GROUP_NAME))
   .build();
  scheduler.rescheduleJob(triggerKey, newTrigger);
  result = true;
  } else {
  logger.error("update job name:{},group name:{} or trigger name:{},group name:{} not exists..",
   jobKey.getName(), jobKey.getGroup(), triggerKey.getName(), triggerKey.getGroup());
  }
 } catch (SchedulerException e) {
  logger.error(e.getMessage(), e);
  logger.error("update job name:{},group name:{} failed!", jobKey.getName(), jobKey.getGroup());
 }
 return result;
 }

 public boolean deleteJob(String jobName) {
 boolean result = false;
 JobKey jobKey = new JobKey(jobName, JOB_GROUP_NAME);
 try {
  if (scheduler.checkExists(jobKey)) {
  result = scheduler.deleteJob(jobKey);
  } else {
  logger.error("delete job name:{},group name:{} not exists.", jobKey.getName(), jobKey.getGroup());
  }
 } catch (SchedulerException e) {
  logger.error(e.getMessage(), e);
  logger.error("delete job name:{},group name:{} failed!", jobKey.getName(), jobKey.getGroup());
 }
 return result;
 }

 @Override
 public void setApplicationContext(ApplicationContext applicationContext) throws BeansException {
 this.applicationContext = applicationContext;
 }

}

6、創建定時任務啟動類

項目運行時給spring註入定時任務

/**
 * 定時任務啟動類
 */
@Component
public class JobRunner implements ApplicationRunner {

 //註入定時任務管理器
 @Autowired
 private JobQuartzManager quartzManager;

 /**
 * 項目啟動時激活定時任務
 */
 @Override
 public void run(ApplicationArguments applicationArguments) {
 System.out.println("--------------------註入定時任務---------------------");
 quartzManager.start();
 System.out.println("--------------------定時任務註入完成---------------------");
 }

}

7、測試案例

@RestController
@RequestMapping("/job")
public class JobController {

 @Autowired
 JobQuartzManager quartzManager;

 @PostMapping("addJob")
 @ResponseBody
 public String addJob(@RequestParam("dataBaseId") Long dataBaseId, @RequestParam("cronExp") String cronExp){
 boolean success = quartzManager.addJob("job" + dataBaseId, dataBaseId, JobTask.class, cronExp);
 if(success){
  return "添加成功";
 }else{
  return "添加失敗!";
 }
 }

 @PostMapping("deleteJob")
 @ResponseBody
 public String deleteJob(@RequestParam("jobName") String jobName){
 boolean success = quartzManager.deleteJob(jobName);
 if(success){
  return "刪除成功";
 }else{
  return "刪除失敗!";
 }
 }

 @PostMapping("updateJob")
 @ResponseBody
 public String updateJob(@RequestParam("jobName") String jobName, @RequestParam("cronExp") String cronExp){
 boolean success = quartzManager.updateJob(jobName, cronExp);
 if(success){
  return "更新成功";
 }else{
  return "更新失敗!";
 }
 }

}

總結

到此這篇關於springboot實現動態定時任務的文章就介紹到這瞭,更多相關springboot動態定時任務內容請搜索WalkonNet以前的文章或繼續瀏覽下面的相關文章希望大傢以後多多支持WalkonNet!

推薦閱讀: