最近在做一个定时相关的功能,选择使用quartz来完成。这个过程中自己封装了一个QuartzUtil工具类,并且一步步完善,填了很多坑。相比于其他类似的文章,个人感觉我写的这个工具类还算是比较完善的一个了。
我也写了一个简单的demo项目,用来帮助你更好的理解,公众号回复【github】获取项目github地址,该项目我会一直保持更新。
主要实现功能如下:
基于quartz2.3.1实现动态管理定时任务。
使用swagger实现接口文档。
前后端统一使用JSON格式交互。
当然也可以直接带走这个工具类,类中使用了我自定义的一个异常类和一个枚举类,都一起放在下面了。个人并未配置quartz.properties,使用时只需添加quartz依赖,然后将quartzUtil和两个相关的类放到项目中即可。
一、项目swagger文档
二、项目Maven依赖
很巧都是基于2.3.1版本。
(1) springboot版本
org.springframework.boot spring-boot-starter-parent 2.3.1.RELEASE
(2) quartz依赖
org.quartz-scheduler quartz 2.3.1
三、quartz工具类
在QuartzUtil中用到了我自定义的异常类CustomException和枚举类Code。
(1) CustomException类
/** * @author frost2 * @date 2020-9-23 17:23:38 */@ToString@Getter@Setterpublic class CustomException extends RuntimeException {
public CustomException(int code, String msg) {
this.code = code; this.msg = msg; } public CustomException(Code code) {
this.code = code.getCode(); this.msg = code.getMsg(); } private int code; private String msg;}
(2) Code类
为了不让篇幅太长,我只保留QuartzUtil中用到的状态码。
/** * @author frost2 * @date 2020-9-23 17:23:43 */@ToString@Getterpublic enum Code {
PARAM_FORMAT_ERROR(2004, "参数异常"), EXECUTION_ERROR(6002, "接口执行失败"); //枚举的属性字段必须是私有且不可变 private