服务器之家:专注于服务器技术及软件下载分享
分类导航

PHP教程|ASP.NET教程|Java教程|ASP教程|编程技术|正则表达式|C/C++|IOS|C#|Swift|Android|VB|R语言|JavaScript|易语言|vb.net|

服务器之家 - 编程语言 - Java教程 - SpringBoot实现quartz定时任务可视化管理功能

SpringBoot实现quartz定时任务可视化管理功能

2021-12-09 12:51code2roc Java教程

这篇文章主要介绍了SpringBoot实现quartz定时任务可视化管理功能,本文通过实例代码给大家介绍的非常详细,对大家的学习或工作具有一定的参考借鉴价值,需要的朋友可以参考下

前言

在实际框架或产品开发过程中,springboot中集成quarzt方式基本是以job和trigger的bean对象方式直接硬编码完成的,例如以下代码示例。对于系统内定义的所有定时任务类型,具体执行类,执行策略,运行状态都没有一个动态全局的管理,所有决定将quartz做成可视化配置管理,便于统一管理,也降低了使用门槛,只需要关心job类的实现即可

?
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
@Bean
   public JobDetail SMSJobDetail() {
       return JobBuilder.newJob(SMSJob.class).withIdentity("SMSJob").storeDurably().build();
   }
 
   // 把jobDetail注册到trigger上去
   @Bean
   public Trigger myJobTrigger() {
       SimpleScheduleBuilder scheduleBuilder = SimpleScheduleBuilder.simpleSchedule()
               .withIntervalInSeconds(1).repeatForever();
 
       return TriggerBuilder.newTrigger()
               .forJob(SMSJobDetail())
               .withIdentity("myJobTrigger")
               .withSchedule(scheduleBuilder)
               .build();
   }

表结构

用于存储quartz配置

?
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
DROP TABLE IF EXISTS `f_quartztask`;
CREATE TABLE `f_quartztask` (
  `TaskID` varchar(50) NOT NULL,
  `TaskName` varchar(200) DEFAULT NULL,
  `TaskType` int(11) DEFAULT NULL,
  `TaskTag` varchar(100) DEFAULT NULL,
  `JobClassPath` varchar(200) DEFAULT NULL,
  `ExecutePeroid` int(11) DEFAULT NULL,
  `ExecuteUnit` int(11) DEFAULT NULL,
  `CornExpress` varchar(200) DEFAULT NULL,
  `Enviroment` varchar(50) DEFAULT NULL,
  `TaskStatus` int(11) DEFAULT NULL,
  `SortNum` int(11) DEFAULT NULL,
  `Remark` varchar(500) DEFAULT NULL,
  PRIMARY KEY (`TaskID`)
) ENGINE=InnoDB DEFAULT CHARSET=utf8mb4;

枚举类

?
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
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
public class QuartzEnum {
    public enum TaskType implements IConvertEnumToCodeItem {
        Cycle(10, "循环任务"), Corn(20, "Corn表达式任务");
        private int _value;
        private String _name;
 
        private TaskType(int value, String name) {
            set_value(value);
            set_name((name));
        }
 
        public int get_value() {
            return _value;
        }
 
        public void set_value(int _value) {
            this._value = _value;
        }
 
        public String get_name() {
            return _name;
        }
 
        public void set_name(String _name) {
            this._name = _name;
        }
 
        @Override
        public String toString() {
            return _name;
        }
 
        @Override
        public String getCodeName() {
            return "Quartz任务类别";
        }
    }
 
    public enum ExecuteUnit implements IConvertEnumToCodeItem {
        Second(10, "秒"), Minute(20, "分"), Hour(30, "时");
        private int _value;
        private String _name;
 
        private ExecuteUnit(int value, String name) {
            set_value(value);
            set_name((name));
        }
 
        public int get_value() {
            return _value;
        }
 
        public void set_value(int _value) {
            this._value = _value;
        }
 
        public String get_name() {
            return _name;
        }
 
        public void set_name(String _name) {
            this._name = _name;
        }
 
        @Override
        public String toString() {
            return _name;
        }
 
        @Override
        public String getCodeName() {
            return "Quartz间隔单位";
        }
    }
 
 
    public enum TaskStatus implements IConvertEnumToCodeItem {
        Open(10, "开启"), Close(20, "关闭");
        private int _value;
        private String _name;
 
        private TaskStatus(int value, String name) {
            set_value(value);
            set_name((name));
        }
 
        public int get_value() {
            return _value;
        }
 
        public void set_value(int _value) {
            this._value = _value;
        }
 
        public String get_name() {
            return _name;
        }
 
        public void set_name(String _name) {
            this._name = _name;
        }
 
        @Override
        public String toString() {
            return _name;
        }
 
        @Override
        public String getCodeName() {
            return "Quartz任务状态";
        }
    }
 
    public enum TaskEnviroment implements IConvertEnumToCodeItem {
        All("全部", "全部"), Dev("dev", "开发环境"), Pro("pro", "正式环境");
        private String _value;
        private String _name;
 
        private TaskEnviroment(String value, String name) {
            set_value(value);
            set_name((name));
        }
 
        public String get_value() {
            return _value;
        }
 
        public void set_value(String _value) {
            this._value = _value;
        }
 
        public String get_name() {
            return _name;
        }
 
        public void set_name(String _name) {
            this._name = _name;
        }
 
        @Override
        public String toString() {
            return _name;
        }
 
        @Override
        public String getCodeName() {
            return "Quartz任务执行环境";
        }
    }
}

QuartzFactory

支持Job类注bean入对象

?
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
@Component
public class QuartzFactory extends AdaptableJobFactory {
    @Autowired
    private AutowireCapableBeanFactory capableBeanFactory;
 
    @Override
    protected Object createJobInstance(TriggerFiredBundle bundle) throws Exception {
        // 调用父类的方法
        Object jobInstance = super.createJobInstance(bundle);
        // 进行注入
        capableBeanFactory.autowireBean(jobInstance);
        return jobInstance;
 
    }
}

QuartzConfig

注入QuartzFactory对象

?
1
2
3
4
5
6
7
8
9
10
11
12
13
@Configuration
public class QuartzConfig {
    @Autowired
    private QuartzFactory quartzFactory;
 
    @Bean
    public SchedulerFactoryBean schedulerFactoryBean(){
        SchedulerFactoryBean schedulerFactoryBean = new SchedulerFactoryBean();
        schedulerFactoryBean.setJobFactory(quartzFactory);
        //将job实例化,能够操作进行Spring 注入
        return schedulerFactoryBean;
    }
}

QuartzUtil

定时任务动态添加/删除操作类,initQuartzTask方法在系统启动时执行,根据配置自动开启相关符合条件的任务

?
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
93
94
95
96
97
98
99
100
101
102
103
104
105
106
@Component
public class QuartzUtil {
    @Autowired
    private SchedulerFactoryBean schedulerFactoryBean;
    @Autowired
    private F_QuartzTaskService quartzTaskService;
    @Value("${spring.profiles.active}")
    private String active;
    private static String JOB_GROUP_NAME = "DEFAULT_JOB_GROUP_NAME";
    private static String TRIGGER_GROUP_NAME = "DEFAULT_TRIGGER_GROUP_NAME";
 
 
    public void initQuartzTask() {
        List<F_QuartzTaskDO> openTaskList = quartzTaskService.selectAllList();
        if(openTaskList.size()>0){
            openTaskList = openTaskList.stream().filter(a -> a.getTaskStatus() == QuartzEnum.TaskStatus.Open.get_value() &&
                    (a.getEnviroment().equals(QuartzEnum.TaskEnviroment.All.get_name()) || a.getEnviroment().equals(active))).collect(Collectors.toList());
        }
        for (F_QuartzTaskDO taskDO : openTaskList) {
            try {
                Class<Job> jobClass = (Class<Job>) Class.forName(taskDO.getJobClassPath());
                if (taskDO.getTaskType() == QuartzEnum.TaskType.Cycle.get_value()) {
                    addIntervalJob(taskDO.getTaskTag(), jobClass, taskDO.getExecutePeroid(), taskDO.getExecuteUnit());
                } else {
                    addCornJob(taskDO.getTaskTag(), jobClass, taskDO.getCornExpress());
                }
            } catch (Exception e) {
                e.printStackTrace();
            }
        }
        if (openTaskList.size() > 0) {
            System.out.println("扫描并初始化开启quartz定时任务成功,任务数量:" + openTaskList.size() + "个");
        }
    }
 
    public void startTask( F_QuartzTaskDO taskDO){
        try {
            Class<Job> jobClass = (Class<Job>) Class.forName(taskDO.getJobClassPath());
            if (taskDO.getTaskType() == QuartzEnum.TaskType.Cycle.get_value()) {
                addIntervalJob(taskDO.getTaskTag(), jobClass, taskDO.getExecutePeroid(), taskDO.getExecuteUnit());
            } else {
                addCornJob(taskDO.getTaskTag(), jobClass, taskDO.getCornExpress());
            }
        } catch (Exception e) {
            e.printStackTrace();
        }
    }
 
    //增加定时任务任务
    public void addIntervalJob(String jobName, Class<? extends Job> cls, int peroid, int timeUnit) {
        try {
            SimpleScheduleBuilder scheduleBuilder = null;
            if (timeUnit == QuartzEnum.ExecuteUnit.Second.get_value()) {
                scheduleBuilder = SimpleScheduleBuilder.simpleSchedule().withIntervalInSeconds(peroid).repeatForever();
            } else if (timeUnit == QuartzEnum.ExecuteUnit.Minute.get_value()) {
                scheduleBuilder = SimpleScheduleBuilder.simpleSchedule().withIntervalInMinutes(peroid).repeatForever();
            } else if (timeUnit == QuartzEnum.ExecuteUnit.Hour.get_value()) {
                scheduleBuilder = SimpleScheduleBuilder.simpleSchedule().withIntervalInHours(peroid).repeatForever();
            }
            Scheduler sched = schedulerFactoryBean.getScheduler();
            JobDetail jobDetail = JobBuilder.newJob(cls).withIdentity(jobName, JOB_GROUP_NAME).storeDurably().build();
            Trigger trigger = TriggerBuilder.newTrigger().forJob(jobDetail).withIdentity(jobName, TRIGGER_GROUP_NAME).withSchedule(scheduleBuilder).build();
 
            sched.scheduleJob(jobDetail, trigger);
            if (!sched.isShutdown()) {
                sched.start();        // 启动
            }
        } catch (Exception e) {
            throw new RuntimeException(e);
        }
    }
 
    //增加corn表达式任务
    public void addCornJob(String jobName, Class<? extends Job> cls, String cornExpress) {
        try {
            Scheduler sched = schedulerFactoryBean.getScheduler();
            JobDetail jobDetail = JobBuilder.newJob(cls).withIdentity(jobName, JOB_GROUP_NAME).build();
            CronTrigger trigger = (CronTrigger) TriggerBuilder
                    .newTrigger()
                    .withIdentity(jobName, TRIGGER_GROUP_NAME)
                    .withSchedule(CronScheduleBuilder.cronSchedule(cornExpress))
                    .build();
            sched.scheduleJob(jobDetail, trigger);
            if (!sched.isShutdown()) {
                sched.start();        // 启动
            }
        } catch (Exception e) {
            throw new RuntimeException(e);
        }
    }
 
    //停止任务
    public void deleteJob(String jobName) {
        try {
            Scheduler sched = schedulerFactoryBean.getScheduler();
            TriggerKey triggerKey = TriggerKey.triggerKey(jobName, TRIGGER_GROUP_NAME);
            JobKey jobKey = JobKey.jobKey(jobName, JOB_GROUP_NAME);
            sched.pauseTrigger(triggerKey); // 停止触发器
            sched.unscheduleJob(triggerKey);// 移除触发器
            sched.deleteJob(jobKey);        // 删除任务
        } catch (Exception e) {
            throw new RuntimeException(e);
        }
    }
 
}

界面展示

SpringBoot实现quartz定时任务可视化管理功能

SpringBoot实现quartz定时任务可视化管理功能

到此这篇关于SpringBoot实现quartz定时任务可视化管理的文章就介绍到这了,更多相关SpringBoot 定时任务可视化内容请搜索服务器之家以前的文章或继续浏览下面的相关文章希望大家以后多多支持服务器之家!

原文链接:https://blog.csdn.net/u013407099/article/details/119978407

延伸 · 阅读

精彩推荐
  • Java教程小米推送Java代码

    小米推送Java代码

    今天小编就为大家分享一篇关于小米推送Java代码,小编觉得内容挺不错的,现在分享给大家,具有很好的参考价值,需要的朋友一起跟随小编来看看吧...

    富贵稳中求8032021-07-12
  • Java教程20个非常实用的Java程序代码片段

    20个非常实用的Java程序代码片段

    这篇文章主要为大家分享了20个非常实用的Java程序片段,对java开发项目有所帮助,感兴趣的小伙伴们可以参考一下 ...

    lijiao5352020-04-06
  • Java教程xml与Java对象的转换详解

    xml与Java对象的转换详解

    这篇文章主要介绍了xml与Java对象的转换详解的相关资料,需要的朋友可以参考下...

    Java教程网2942020-09-17
  • Java教程升级IDEA后Lombok不能使用的解决方法

    升级IDEA后Lombok不能使用的解决方法

    最近看到提示IDEA提示升级,寻思已经有好久没有升过级了。升级完毕重启之后,突然发现好多错误,本文就来介绍一下如何解决,感兴趣的可以了解一下...

    程序猿DD9332021-10-08
  • Java教程Java实现抢红包功能

    Java实现抢红包功能

    这篇文章主要为大家详细介绍了Java实现抢红包功能,采用多线程模拟多人同时抢红包,文中示例代码介绍的非常详细,具有一定的参考价值,感兴趣的小伙...

    littleschemer13532021-05-16
  • Java教程Java BufferWriter写文件写不进去或缺失数据的解决

    Java BufferWriter写文件写不进去或缺失数据的解决

    这篇文章主要介绍了Java BufferWriter写文件写不进去或缺失数据的解决方案,具有很好的参考价值,希望对大家有所帮助。如有错误或未考虑完全的地方,望...

    spcoder14552021-10-18
  • Java教程Java8中Stream使用的一个注意事项

    Java8中Stream使用的一个注意事项

    最近在工作中发现了对于集合操作转换的神器,java8新特性 stream,但在使用中遇到了一个非常重要的注意点,所以这篇文章主要给大家介绍了关于Java8中S...

    阿杜7482021-02-04
  • Java教程Java使用SAX解析xml的示例

    Java使用SAX解析xml的示例

    这篇文章主要介绍了Java使用SAX解析xml的示例,帮助大家更好的理解和学习使用Java,感兴趣的朋友可以了解下...

    大行者10067412021-08-30