激情久久久_欧美视频区_成人av免费_不卡视频一二三区_欧美精品在欧美一区二区少妇_欧美一区二区三区的

服務(wù)器之家:專注于服務(wù)器技術(shù)及軟件下載分享
分類導(dǎo)航

PHP教程|ASP.NET教程|Java教程|ASP教程|編程技術(shù)|正則表達(dá)式|C/C++|IOS|C#|Swift|Android|VB|R語言|JavaScript|易語言|vb.net|

服務(wù)器之家 - 編程語言 - Java教程 - Spring Boot如何實(shí)現(xiàn)定時任務(wù)的動態(tài)增刪啟停詳解

Spring Boot如何實(shí)現(xiàn)定時任務(wù)的動態(tài)增刪啟停詳解

2020-07-20 11:38極客網(wǎng) Java教程

這篇文章主要給大家介紹了關(guān)于Spring Boot如何實(shí)現(xiàn)定時任務(wù)的動態(tài)增刪啟停的相關(guān)資料,文中通過示例代碼以及圖文介紹的非常詳細(xì),對大家的學(xué)習(xí)或者工作具有一定的參考學(xué)習(xí)價值,需要的朋友們下面來一起學(xué)習(xí)學(xué)習(xí)吧

我以為動態(tài)停啟定時任務(wù)一般用quartz,沒想到還可以通過ScheduledTaskRegistrar來拓展。但是分布式場景,建議還是用quartz吧!

在 spring boot 項(xiàng)目中,可以通過 @EnableScheduling 注解和 @Scheduled 注解實(shí)現(xiàn)定時任務(wù),也可以通過 SchedulingConfigurer 接口來實(shí)現(xiàn)定時任務(wù)。但是這兩種方式不能動態(tài)添加、刪除、啟動、停止任務(wù)。要實(shí)現(xiàn)動態(tài)增刪啟停定時任務(wù)功能,比較廣泛的做法是集成 Quartz 框架。

但是本人的開發(fā)原則是:在滿足項(xiàng)目需求的情況下,盡量少的依賴其它框架,避免項(xiàng)目過于臃腫和復(fù)雜。查看 spring-context 這個 jar 包中 org.springframework.scheduling.ScheduledTaskRegistrar 這個類的源代碼,發(fā)現(xiàn)可以通過改造這個類就能實(shí)現(xiàn)動態(tài)增刪啟停定時任務(wù)功能。

Spring Boot如何實(shí)現(xiàn)定時任務(wù)的動態(tài)增刪啟停詳解

定時任務(wù)列表頁

Spring Boot如何實(shí)現(xiàn)定時任務(wù)的動態(tài)增刪啟停詳解

定時任務(wù)執(zhí)行日志

添加執(zhí)行定時任務(wù)的線程池配置類

?
1
2
3
4
5
6
7
8
9
10
11
12
@Configuration
public class SchedulingConfig {
 @Bean
 public TaskScheduler taskScheduler() {
  ThreadPoolTaskScheduler taskScheduler = new ThreadPoolTaskScheduler();
  
  taskScheduler.setPoolSize(4);
  taskScheduler.setRemoveOnCancelPolicy(true);
  taskScheduler.setThreadNamePrefix("TaskSchedulerThreadPool-");
  return taskScheduler;
 }
}

添加 ScheduledFuture 的包裝類。ScheduledFuture 是 ScheduledExecutorService 定時任務(wù)線程池的執(zhí)行結(jié)果。

?
1
2
3
4
5
6
7
8
9
10
11
12
public final class ScheduledTask {
 
 volatile ScheduledFuture<?> future;
 
 
 public void cancel() {
  ScheduledFuture<?> future = this.future;
  if (future != null) {
   future.cancel(true);
  }
 }
}

添加 Runnable 接口實(shí)現(xiàn)類,被定時任務(wù)線程池調(diào)用,用來執(zhí)行指定 bean 里面的方法。

?
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
public class SchedulingRunnable implements Runnable {
 
 private static final Logger logger = LoggerFactory.getLogger(SchedulingRunnable.class);
 
 private String beanName;
 
 private String methodName;
 
 private String params;
 
 public SchedulingRunnable(String beanName, String methodName) {
  this(beanName, methodName, null);
 }
 
 public SchedulingRunnable(String beanName, String methodName, String params) {
  this.beanName = beanName;
  this.methodName = methodName;
  this.params = params;
 }
 
 @Override
 public void run() {
  logger.info("定時任務(wù)開始執(zhí)行 - bean:{},方法:{},參數(shù):{}", beanName, methodName, params);
  long startTime = System.currentTimeMillis();
 
  try {
   Object target = SpringContextUtils.getBean(beanName);
 
   Method method = null;
   if (StringUtils.isNotEmpty(params)) {
    method = target.getClass().getDeclaredMethod(methodName, String.class);
   } else {
    method = target.getClass().getDeclaredMethod(methodName);
   }
 
   ReflectionUtils.makeAccessible(method);
   if (StringUtils.isNotEmpty(params)) {
    method.invoke(target, params);
   } else {
    method.invoke(target);
   }
  } catch (Exception ex) {
   logger.error(String.format("定時任務(wù)執(zhí)行異常 - bean:%s,方法:%s,參數(shù):%s ", beanName, methodName, params), ex);
  }
 
  long times = System.currentTimeMillis() - startTime;
  logger.info("定時任務(wù)執(zhí)行結(jié)束 - bean:{},方法:{},參數(shù):{},耗時:{} 毫秒", beanName, methodName, params, times);
 }
 
 @Override
 public boolean equals(Object o) {
  if (this == o) return true;
  if (o == null || getClass() != o.getClass()) return false;
  SchedulingRunnable that = (SchedulingRunnable) o;
  if (params == null) {
   return beanName.equals(that.beanName) &&
     methodName.equals(that.methodName) &&
     that.params == null;
  }
 
  return beanName.equals(that.beanName) &&
    methodName.equals(that.methodName) &&
    params.equals(that.params);
 }
 
 @Override
 public int hashCode() {
  if (params == null) {
   return Objects.hash(beanName, methodName);
  }
 
  return Objects.hash(beanName, methodName, params);
 }
}

添加定時任務(wù)注冊類,用來增加、刪除定時任務(wù)。

?
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
@Component
public class CronTaskRegistrar implements DisposableBean {
 
 private final Map<Runnable, ScheduledTask> scheduledTasks = new ConcurrentHashMap<>(16);
 
 @Autowired
 private TaskScheduler taskScheduler;
 
 public TaskScheduler getScheduler() {
  return this.taskScheduler;
 }
 
 public void addCronTask(Runnable task, String cronExpression) {
  addCronTask(new CronTask(task, cronExpression));
 }
 
 public void addCronTask(CronTask cronTask) {
  if (cronTask != null) {
   Runnable task = cronTask.getRunnable();
   if (this.scheduledTasks.containsKey(task)) {
    removeCronTask(task);
   }
 
   this.scheduledTasks.put(task, scheduleCronTask(cronTask));
  }
 }
 
 public void removeCronTask(Runnable task) {
  ScheduledTask scheduledTask = this.scheduledTasks.remove(task);
  if (scheduledTask != null)
   scheduledTask.cancel();
 }
 
 public ScheduledTask scheduleCronTask(CronTask cronTask) {
  ScheduledTask scheduledTask = new ScheduledTask();
  scheduledTask.future = this.taskScheduler.schedule(cronTask.getRunnable(), cronTask.getTrigger());
 
  return scheduledTask;
 }
 
 
 @Override
 public void destroy() {
  for (ScheduledTask task : this.scheduledTasks.values()) {
   task.cancel();
  }
 
  this.scheduledTasks.clear();
 }
}

添加定時任務(wù)示例類

?
1
2
3
4
5
6
7
8
9
10
@Component("demoTask")
public class DemoTask {
 public void taskWithParams(String params) {
  System.out.println("執(zhí)行有參示例任務(wù):" + params);
 }
 
 public void taskNoParams() {
  System.out.println("執(zhí)行無參示例任務(wù)");
 }
}

定時任務(wù)數(shù)據(jù)庫表設(shè)計(jì)

Spring Boot如何實(shí)現(xiàn)定時任務(wù)的動態(tài)增刪啟停詳解

定時任務(wù)數(shù)據(jù)庫表設(shè)計(jì)

添加定時任務(wù)實(shí)體類

?
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
public class SysJobPO {
 
 private Integer jobId;
 
 private String beanName;
 
 private String methodName;
 
 private String methodParams;
 
 private String cronExpression;
 
 private Integer jobStatus;
 
 private String remark;
 
 private Date createTime;
 
 private Date updateTime;
 
 public Integer getJobId() {
  return jobId;
 }
 
 public void setJobId(Integer jobId) {
  this.jobId = jobId;
 }
 
 public String getBeanName() {
  return beanName;
 }
 
 public void setBeanName(String beanName) {
  this.beanName = beanName;
 }
 
 public String getMethodName() {
  return methodName;
 }
 
 public void setMethodName(String methodName) {
  this.methodName = methodName;
 }
 
 public String getMethodParams() {
  return methodParams;
 }
 
 public void setMethodParams(String methodParams) {
  this.methodParams = methodParams;
 }
 
 public String getCronExpression() {
  return cronExpression;
 }
 
 public void setCronExpression(String cronExpression) {
  this.cronExpression = cronExpression;
 }
 
 public Integer getJobStatus() {
  return jobStatus;
 }
 
 public void setJobStatus(Integer jobStatus) {
  this.jobStatus = jobStatus;
 }
 
 public String getRemark() {
  return remark;
 }
 
 public void setRemark(String remark) {
  this.remark = remark;
 }
 
 public Date getCreateTime() {
  return createTime;
 }
 
 public void setCreateTime(Date createTime) {
  this.createTime = createTime;
 }
 
 public Date getUpdateTime() {
  return updateTime;
 }
 
 public void setUpdateTime(Date updateTime) {
  this.updateTime = updateTime;
 }
}

新增定時任務(wù)

Spring Boot如何實(shí)現(xiàn)定時任務(wù)的動態(tài)增刪啟停詳解

新增定時任務(wù)

?
1
2
3
4
5
6
7
8
9
10
11
boolean success = sysJobRepository.addSysJob(sysJob);
if (!success)
 return OperationResUtils.fail("新增失敗");
else {
 if (sysJob.getJobStatus().equals(SysJobStatus.NORMAL.ordinal())) {
  SchedulingRunnable task = new SchedulingRunnable(sysJob.getBeanName(), sysJob.getMethodName(), sysJob.getMethodParams());
  cronTaskRegistrar.addCronTask(task, sysJob.getCronExpression());
 }
}
 
return OperationResUtils.success();

修改定時任務(wù),先移除原來的任務(wù),再啟動新任務(wù)

?
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
boolean success = sysJobRepository.editSysJob(sysJob);
if (!success)
 return OperationResUtils.fail("編輯失敗");
else {
 
 if (existedSysJob.getJobStatus().equals(SysJobStatus.NORMAL.ordinal())) {
  SchedulingRunnable task = new SchedulingRunnable(existedSysJob.getBeanName(), existedSysJob.getMethodName(), existedSysJob.getMethodParams());
  cronTaskRegistrar.removeCronTask(task);
 }
 
 if (sysJob.getJobStatus().equals(SysJobStatus.NORMAL.ordinal())) {
  SchedulingRunnable task = new SchedulingRunnable(sysJob.getBeanName(), sysJob.getMethodName(), sysJob.getMethodParams());
  cronTaskRegistrar.addCronTask(task, sysJob.getCronExpression());
 }
}
 
return OperationResUtils.success();

刪除定時任務(wù)

?
1
2
3
4
5
6
7
8
9
10
11
boolean success = sysJobRepository.deleteSysJobById(req.getJobId());
if (!success)
 return OperationResUtils.fail("刪除失敗");
else{
 if (existedSysJob.getJobStatus().equals(SysJobStatus.NORMAL.ordinal())) {
  SchedulingRunnable task = new SchedulingRunnable(existedSysJob.getBeanName(), existedSysJob.getMethodName(), existedSysJob.getMethodParams());
  cronTaskRegistrar.removeCronTask(task);
 }
}
 
return OperationResUtils.success();

定時任務(wù)啟動 / 停止?fàn)顟B(tài)切換

?
1
2
3
4
5
6
7
if (existedSysJob.getJobStatus().equals(SysJobStatus.NORMAL.ordinal())) {
 SchedulingRunnable task = new SchedulingRunnable(existedSysJob.getBeanName(), existedSysJob.getMethodName(), existedSysJob.getMethodParams());
 cronTaskRegistrar.addCronTask(task, existedSysJob.getCronExpression());
} else {
 SchedulingRunnable task = new SchedulingRunnable(existedSysJob.getBeanName(), existedSysJob.getMethodName(), existedSysJob.getMethodParams());
 cronTaskRegistrar.removeCronTask(task);
}

添加實(shí)現(xiàn)了 CommandLineRunner 接口的 SysJobRunner 類,當(dāng) spring boot 項(xiàng)目啟動完成后,加載數(shù)據(jù)庫里狀態(tài)為正常的定時任務(wù)。

?
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
@Service
public class SysJobRunner implements CommandLineRunner {
 
 private static final Logger logger = LoggerFactory.getLogger(SysJobRunner.class);
 
 @Autowired
 private ISysJobRepository sysJobRepository;
 
 @Autowired
 private CronTaskRegistrar cronTaskRegistrar;
 
 @Override
 public void run(String... args) {
  
  List<SysJobPO> jobList = sysJobRepository.getSysJobListByStatus(SysJobStatus.NORMAL.ordinal());
  if (CollectionUtils.isNotEmpty(jobList)) {
   for (SysJobPO job : jobList) {
    SchedulingRunnable task = new SchedulingRunnable(job.getBeanName(), job.getMethodName(), job.getMethodParams());
    cronTaskRegistrar.addCronTask(task, job.getCronExpression());
   }
 
   logger.info("定時任務(wù)已加載完畢...");
  }
 }
}

工具類 SpringContextUtils,用來從 spring 容器里獲取 bean

?
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
@Component
public class SpringContextUtils implements ApplicationContextAware {
 
 private static ApplicationContext applicationContext;
 
 @Override
 public void setApplicationContext(ApplicationContext applicationContext)
   throws BeansException {
  SpringContextUtils.applicationContext = applicationContext;
 }
 
 public static Object getBean(String name) {
  return applicationContext.getBean(name);
 }
 
 public static <T> T getBean(Class<T> requiredType) {
  return applicationContext.getBean(requiredType);
 }
 
 public static <T> T getBean(String name, Class<T> requiredType) {
  return applicationContext.getBean(name, requiredType);
 }
 
 public static boolean containsBean(String name) {
  return applicationContext.containsBean(name);
 }
 
 public static boolean isSingleton(String name) {
  return applicationContext.isSingleton(name);
 }
 
 public static Class<? extends Object> getType(String name) {
  return applicationContext.getType(name);
 }
}

總結(jié)

到此這篇關(guān)于Spring Boot如何實(shí)現(xiàn)定時任務(wù)的動態(tài)增刪啟停的文章就介紹到這了,更多相關(guān)SpringBoot定時任務(wù)的動態(tài)增刪啟停內(nèi)容請搜索服務(wù)器之家以前的文章或繼續(xù)瀏覽下面的相關(guān)文章希望大家以后多多支持服務(wù)器之家!

原文鏈接:https://www.geek521.com/2020/07/18/springboot實(shí)現(xiàn)定時任務(wù)的動態(tài)增刪啟停/

延伸 · 閱讀

精彩推薦
主站蜘蛛池模板: 色交视频 | 天天舔夜夜操 | 成人福利在线免费观看 | 男女污视频在线观看 | 成人在线观看免费观看 | 国产在线播放91 | 免费观看黄色片视频 | 欧美在线国产 | 国产中出在线观看 | 性少妇videosexfreexx | 97香蕉超级碰碰久久免费软件 | 成人精品一区二区三区中文字幕 | 天堂成人一区二区三区 | 国产亚洲精品成人 | 国产影院在线观看 | 九九精品视频免费 | 免费黄色在线电影 | 成人在线观看免费爱爱 | 国外成人在线视频 | 国产资源在线观看视频 | 亚洲国产精品久久久久制服红楼梦 | 高清国产在线 | 亚洲综合网站 | 操碰97 | 欧美黄色一级片在线观看 | 永久免费不卡在线观看黄网站 | 精品国产成人 | 国产毛片在线高清视频 | 久久精品小短片 | 最新在线黄色网址 | 亚洲成人免费电影 | 午夜激情视频免费 | 99re66热这里只有精品8 | 黄色片视频观看 | 视频国产一区二区 | 电影av在线 | 久久亚洲精选 | 特大黑人videos与另类娇小 | 一级毛片免费高清 | 亚洲国产精品久久久久制服红楼梦 | 九九热视频在线 |