Compare commits
12 Commits
95a590f088
...
feat/sched
| Author | SHA1 | Date | |
|---|---|---|---|
|
|
90433695e4 | ||
|
|
e846e7b8a7 | ||
|
|
64d7ca9b67 | ||
|
|
5fb186a85b | ||
|
|
c1f7305b69 | ||
|
|
720f67f30d | ||
|
|
ca95c335df | ||
|
|
e048470e61 | ||
|
|
73dcafa3c4 | ||
|
|
afa610ecaa | ||
|
|
51f0803eab | ||
|
|
64ca6f4478 |
2
pom.xml
2
pom.xml
@@ -46,7 +46,7 @@
|
||||
<dependency>
|
||||
<groupId>com.xiang.starter</groupId>
|
||||
<artifactId>xmc-logger-starter</artifactId>
|
||||
<version>1.0</version>
|
||||
<version>1.1</version>
|
||||
</dependency>
|
||||
</dependencies>
|
||||
|
||||
|
||||
48
readme.md
Normal file
48
readme.md
Normal file
@@ -0,0 +1,48 @@
|
||||
# Xxz-job任务调度系统
|
||||
|
||||
### (一)
|
||||
|
||||
### (二)版本控制
|
||||
|
||||
#### (1)v1.0版本-master分支上
|
||||
|
||||
1. 设计Xxz-job注解以及EnableXxzJob注解,编写xxz-job注解扫描器以及注解执行器,本机单机执行任务。
|
||||
|
||||
```java
|
||||
// 第一版Xxz-job注解内容
|
||||
@Target(ElementType.METHOD)
|
||||
@Retention(RetentionPolicy.RUNTIME)
|
||||
@Documented
|
||||
public @interface XxzJob {
|
||||
|
||||
/**
|
||||
* bean的名称
|
||||
*
|
||||
* @return
|
||||
*/
|
||||
String name();
|
||||
|
||||
/**
|
||||
* cron调度方法
|
||||
* @return
|
||||
*/
|
||||
String cron();
|
||||
|
||||
boolean enabled() default true;
|
||||
/**
|
||||
* 是否支持多机分布式运行
|
||||
* 若为false:每台机器都会执行一次
|
||||
* 若为true:仅一台机器会执行
|
||||
*
|
||||
* @return
|
||||
*/
|
||||
boolean distributed() default true;
|
||||
}
|
||||
```
|
||||
|
||||
第一版XxzJob注解仅支持单机,并且cron固定的方式进行设计,能够将任务根据cron正常启动。
|
||||
|
||||
#### (2)v1.1版本-feat/schedule_v1_0106
|
||||
|
||||
1. 动态获取定时任务的cron和开关
|
||||
1.
|
||||
@@ -19,4 +19,27 @@
|
||||
<project.build.sourceEncoding>UTF-8</project.build.sourceEncoding>
|
||||
</properties>
|
||||
|
||||
|
||||
<build>
|
||||
<plugins>
|
||||
<plugin>
|
||||
<groupId>org.springframework.boot</groupId>
|
||||
<artifactId>spring-boot-maven-plugin</artifactId>
|
||||
<version>2.3.0.RELEASE</version>
|
||||
<configuration>
|
||||
<classifier>exec</classifier>
|
||||
<!-- 指定该Main Class为全局的唯一入口 -->
|
||||
<mainClass>com.xiang.app.Application</mainClass>
|
||||
<layout>ZIP</layout>
|
||||
</configuration>
|
||||
<executions>
|
||||
<execution>
|
||||
<goals>
|
||||
<goal>repackage</goal><!--可以把依赖的包都打包到生成的Jar包中-->
|
||||
</goals>
|
||||
</execution>
|
||||
</executions>
|
||||
</plugin>
|
||||
</plugins>
|
||||
</build>
|
||||
</project>
|
||||
@@ -81,4 +81,14 @@ public class JobConfigDO implements Serializable {
|
||||
* 上次执行时间
|
||||
*/
|
||||
private LocalDateTime lastRunningTime;
|
||||
|
||||
/**
|
||||
* 版本
|
||||
*/
|
||||
private Integer version;
|
||||
|
||||
/**
|
||||
* 环境
|
||||
*/
|
||||
private Long env;
|
||||
}
|
||||
|
||||
@@ -4,6 +4,9 @@ import lombok.AllArgsConstructor;
|
||||
import lombok.Data;
|
||||
import lombok.NoArgsConstructor;
|
||||
|
||||
import javax.validation.constraints.NotBlank;
|
||||
import javax.validation.constraints.NotNull;
|
||||
|
||||
/**
|
||||
* @Author: xiang
|
||||
* @Date: 2026-01-05 15:49
|
||||
@@ -13,14 +16,19 @@ import lombok.NoArgsConstructor;
|
||||
@NoArgsConstructor
|
||||
public class TaskRegisterRequest {
|
||||
|
||||
@NotNull(message = "命名空间不能为空")
|
||||
private Long env;
|
||||
|
||||
/**
|
||||
* 应用名称
|
||||
*/
|
||||
@NotBlank(message = "应用名称不能为空")
|
||||
private String applicationName;
|
||||
|
||||
/**
|
||||
* 应用地址
|
||||
*/
|
||||
@NotBlank(message = "应用地址不能为空")
|
||||
private String applicationAddress;
|
||||
|
||||
/**
|
||||
|
||||
@@ -13,7 +13,8 @@ import java.util.List;
|
||||
public interface IQuartzConfigManage extends IService<JobConfigDO> {
|
||||
|
||||
|
||||
List<JobConfigDO> selectByAppName(String name);
|
||||
List<JobConfigDO> selectByAppName(String name, Long env);
|
||||
List<JobConfigDO> selectByAppNameAndVersion(String name, Integer version);
|
||||
|
||||
List<JobConfigDO> loadEnabledJobs();
|
||||
|
||||
|
||||
@@ -18,10 +18,20 @@ import java.util.List;
|
||||
@Service
|
||||
public class QuartzConfigManageImpl extends ServiceImpl<IQuartzConfigMapper, JobConfigDO> implements IQuartzConfigManage {
|
||||
@Override
|
||||
public List<JobConfigDO> selectByAppName(String name) {
|
||||
public List<JobConfigDO> selectByAppName(String name, Long env) {
|
||||
LambdaQueryWrapper<JobConfigDO> lqw = Wrappers.lambdaQuery();
|
||||
lqw.eq(JobConfigDO::getApplicationName, name);
|
||||
lqw.eq(JobConfigDO::getDelFlag, 0);
|
||||
lqw.eq(JobConfigDO::getEnv, env);
|
||||
return baseMapper.selectList(lqw);
|
||||
}
|
||||
|
||||
@Override
|
||||
public List<JobConfigDO> selectByAppNameAndVersion(String name, Integer version) {
|
||||
LambdaQueryWrapper<JobConfigDO> lqw = Wrappers.lambdaQuery();
|
||||
lqw.eq(JobConfigDO::getApplicationName, name);
|
||||
lqw.eq(JobConfigDO::getDelFlag, 0);
|
||||
lqw.gt(JobConfigDO::getVersion, version);
|
||||
return baseMapper.selectList(lqw);
|
||||
}
|
||||
|
||||
|
||||
@@ -0,0 +1,36 @@
|
||||
package com.xiang.app.quartz.admin.server;
|
||||
|
||||
import com.xiang.app.quartz.admin.domain.entity.JobConfigDO;
|
||||
import com.xiang.app.quartz.admin.service.ITaskConfigService;
|
||||
import com.xiang.xservice.basic.common.resp.Result;
|
||||
import lombok.RequiredArgsConstructor;
|
||||
import org.springframework.web.bind.annotation.GetMapping;
|
||||
import org.springframework.web.bind.annotation.RequestMapping;
|
||||
import org.springframework.web.bind.annotation.RequestParam;
|
||||
import org.springframework.web.bind.annotation.RestController;
|
||||
|
||||
import java.util.List;
|
||||
|
||||
/**
|
||||
* @Author: xiang
|
||||
* @Date: 2026-01-06 15:05
|
||||
*/
|
||||
@RestController
|
||||
@RequiredArgsConstructor
|
||||
@RequestMapping("/open/quartz/fetch")
|
||||
public class XxzJobFetchController {
|
||||
|
||||
private final ITaskConfigService taskConfigService;
|
||||
@GetMapping("/list")
|
||||
public Result<JobConfigDO> list(@RequestParam("appName") String appName, @RequestParam("env") Long env) {
|
||||
List<JobConfigDO> jobsByAppName = taskConfigService.getJobsByAppName(appName, env);
|
||||
return Result.success(jobsByAppName);
|
||||
}
|
||||
|
||||
@GetMapping("/listByVersion")
|
||||
public Result<JobConfigDO> listByVersion(@RequestParam("appName") String appName,
|
||||
@RequestParam("currVersion") Integer currVersion,
|
||||
@RequestParam("env") Long env) {
|
||||
return Result.success(taskConfigService.getJobsByAppNameAndVersion(appName, currVersion, env));
|
||||
}
|
||||
}
|
||||
@@ -1,8 +1,19 @@
|
||||
package com.xiang.app.quartz.admin.server;
|
||||
|
||||
import com.xiang.app.quartz.admin.domain.req.TaskRegisterRequest;
|
||||
import com.xiang.app.quartz.admin.service.ITaskConfigService;
|
||||
import com.xiang.xservice.basic.common.resp.Result;
|
||||
import lombok.RequiredArgsConstructor;
|
||||
import org.springframework.web.bind.annotation.PostMapping;
|
||||
import org.springframework.web.bind.annotation.RequestBody;
|
||||
import org.springframework.web.bind.annotation.RequestMapping;
|
||||
import org.springframework.web.bind.annotation.RestController;
|
||||
|
||||
import javax.validation.Valid;
|
||||
import javax.validation.constraints.NotEmpty;
|
||||
import javax.validation.constraints.NotNull;
|
||||
import java.util.List;
|
||||
|
||||
/**
|
||||
* @Author: xiang
|
||||
* @Date: 2026-01-06 09:18
|
||||
@@ -10,7 +21,21 @@ import org.springframework.web.bind.annotation.RestController;
|
||||
|
||||
@RestController
|
||||
@RequiredArgsConstructor
|
||||
@RequestMapping("/open/quartz/register")
|
||||
public class XxzJobRegisterController {
|
||||
|
||||
private final ITaskConfigService taskConfigService;
|
||||
|
||||
@PostMapping("/single")
|
||||
public Result<Void> registerSingle(@RequestBody @Valid @NotNull(message = "请求参数不能为空") TaskRegisterRequest request){
|
||||
taskConfigService.registerTask(request);
|
||||
return Result.success();
|
||||
}
|
||||
|
||||
@PostMapping("/batch")
|
||||
public Result<Void> batch(@RequestBody @NotEmpty(message = "请求参数不能为空") @Valid List<TaskRegisterRequest> request) {
|
||||
taskConfigService.registerTasks(request);
|
||||
return Result.success();
|
||||
}
|
||||
|
||||
}
|
||||
|
||||
@@ -1,5 +1,6 @@
|
||||
package com.xiang.app.quartz.admin.service;
|
||||
|
||||
import com.xiang.app.quartz.admin.domain.entity.JobConfigDO;
|
||||
import com.xiang.app.quartz.admin.domain.req.TaskRegisterRequest;
|
||||
|
||||
import java.util.List;
|
||||
@@ -23,4 +24,19 @@ public interface ITaskConfigService {
|
||||
* @return
|
||||
*/
|
||||
boolean registerTasks(List<TaskRegisterRequest> request);
|
||||
|
||||
/**
|
||||
* 根据应用获取任务
|
||||
* @param appName
|
||||
* @return
|
||||
*/
|
||||
List<JobConfigDO> getJobsByAppName(String appName, Long env);
|
||||
|
||||
/**
|
||||
* 根据应用名称和版本获取任务
|
||||
* @param appName
|
||||
* @param version
|
||||
* @return
|
||||
*/
|
||||
List<JobConfigDO> getJobsByAppNameAndVersion(String appName, Integer version, Long env);
|
||||
}
|
||||
|
||||
@@ -14,6 +14,7 @@ import org.springframework.stereotype.Service;
|
||||
import java.util.Collections;
|
||||
import java.util.List;
|
||||
import java.util.Map;
|
||||
import java.util.Objects;
|
||||
import java.util.function.Function;
|
||||
import java.util.stream.Collectors;
|
||||
|
||||
@@ -40,7 +41,8 @@ public class TaskConfigServiceImpl implements ITaskConfigService {
|
||||
return false;
|
||||
}
|
||||
String applicationName = request.get(0).getApplicationName();
|
||||
List<JobConfigDO> jobs = quartzConfigManage.selectByAppName(applicationName);
|
||||
Long env = request.get(0).getEnv();
|
||||
List<JobConfigDO> jobs = quartzConfigManage.selectByAppName(applicationName, env);
|
||||
Map<String, JobConfigDO> existJobs = Maps.newHashMap();
|
||||
if (CollectionUtils.isNotEmpty(jobs)) {
|
||||
existJobs.putAll(jobs.stream().collect(Collectors.toMap(JobConfigDO::getBeanName, Function.identity(), (a, b) -> a)));
|
||||
@@ -67,6 +69,34 @@ public class TaskConfigServiceImpl implements ITaskConfigService {
|
||||
return true;
|
||||
}
|
||||
|
||||
@Override
|
||||
public List<JobConfigDO> getJobsByAppName(String appName, Long env) {
|
||||
return quartzConfigManage.selectByAppName(appName, env);
|
||||
}
|
||||
|
||||
@Override
|
||||
public List<JobConfigDO> getJobsByAppNameAndVersion(String appName, Integer version, Long env) {
|
||||
List<JobConfigDO> jobConfigDOS = quartzConfigManage.selectByAppName(appName, env);
|
||||
Map<String, List<JobConfigDO>> map = Maps.newHashMap();
|
||||
if (CollectionUtils.isNotEmpty(jobConfigDOS)) {
|
||||
map.putAll(jobConfigDOS.stream().collect(Collectors.groupingBy(JobConfigDO::getBeanName)));
|
||||
}
|
||||
Map<String, JobConfigDO> result = Maps.newHashMap();
|
||||
map.forEach((k, v) -> {
|
||||
v.forEach(item -> {
|
||||
if (result.containsKey(k)) {
|
||||
JobConfigDO jobConfigDO = result.get(k);
|
||||
if (item.getVersion() > jobConfigDO.getVersion()) {
|
||||
result.put(k, item);
|
||||
}
|
||||
} else {
|
||||
result.put(k, item);
|
||||
}
|
||||
});
|
||||
});
|
||||
return result.values().stream().toList();
|
||||
}
|
||||
|
||||
private static void putDataIntoDo(TaskRegisterRequest item, JobConfigDO jobConfigDO, String applicationName) {
|
||||
jobConfigDO.setApplicationName(applicationName);
|
||||
jobConfigDO.setApplicationAddress(item.getApplicationAddress());
|
||||
@@ -74,6 +104,7 @@ public class TaskConfigServiceImpl implements ITaskConfigService {
|
||||
jobConfigDO.setCron(item.getCron());
|
||||
jobConfigDO.setClazz(item.getClazz());
|
||||
jobConfigDO.setMethod(item.getMethod());
|
||||
jobConfigDO.setJobSwitch(0);
|
||||
jobConfigDO.setJobSwitch(Objects.isNull(jobConfigDO.getJobSwitch()) ? 0 : jobConfigDO.getJobSwitch());
|
||||
jobConfigDO.setEnv(item.getEnv());
|
||||
}
|
||||
}
|
||||
|
||||
@@ -0,0 +1,34 @@
|
||||
spring:
|
||||
cloud:
|
||||
nacos:
|
||||
discovery:
|
||||
group: DEFAULT_GROUP
|
||||
namespace: 6f603892-e9f7-4ca4-acbc-538fa09ebec0
|
||||
server-addr: general.xiangtech.xyz:8848
|
||||
username: nacos
|
||||
password: nacos
|
||||
datasource:
|
||||
dynamic:
|
||||
primary: master
|
||||
datasource:
|
||||
master:
|
||||
url: jdbc:mysql://rm-bp15t34gqx62jm069ro.mysql.rds.aliyuncs.com:3306/xservice_quartz?useUnicode=true&characterEncoding=utf-8&serverTimezone=Asia/Shanghai&allowMultiQueries=true
|
||||
username: quartz
|
||||
password: quartz@123
|
||||
driver-class-name: com.mysql.cj.jdbc.Driver
|
||||
sshConnect: false
|
||||
|
||||
redis:
|
||||
host: r-bp1wt59a6nfyt4e3ltpd.redis.rds.aliyuncs.com
|
||||
port: 6379
|
||||
password: Xiang0000 # 如果无密码可以省略
|
||||
database: 0
|
||||
timeout: 5000
|
||||
lettuce:
|
||||
pool:
|
||||
max-active: 8
|
||||
max-idle: 8
|
||||
min-idle: 0
|
||||
max-wait: 1000
|
||||
xxz-job:
|
||||
appName: xservice-quartz-admin
|
||||
@@ -2,7 +2,7 @@ server:
|
||||
port: 30030
|
||||
spring:
|
||||
profiles:
|
||||
active: dev
|
||||
active: test
|
||||
application:
|
||||
name: xservice-quartz-admin
|
||||
main:
|
||||
|
||||
@@ -11,7 +11,7 @@
|
||||
|
||||
<groupId>com.xiang.starter</groupId>
|
||||
<artifactId>xservice-quartz-core</artifactId>
|
||||
<version>1.0-SNAPSHOT</version>
|
||||
<version>1.1</version>
|
||||
|
||||
<properties>
|
||||
<maven.compiler.source>17</maven.compiler.source>
|
||||
@@ -25,6 +25,11 @@
|
||||
<artifactId>xmc-common</artifactId>
|
||||
<version>1.0</version>
|
||||
</dependency>
|
||||
<dependency>
|
||||
<groupId>com.xiang.starter</groupId>
|
||||
<artifactId>xmc-http-starter</artifactId>
|
||||
<version>2.0-SNAPSHOT</version>
|
||||
</dependency>
|
||||
<dependency>
|
||||
<groupId>com.xiang.starter</groupId>
|
||||
<artifactId>xmc-cache-starter</artifactId>
|
||||
|
||||
@@ -22,13 +22,13 @@ public @interface XxzJob {
|
||||
*/
|
||||
String name();
|
||||
|
||||
/**
|
||||
* cron调度方法
|
||||
* @return
|
||||
*/
|
||||
String cron();
|
||||
// /**
|
||||
// * cron调度方法
|
||||
// * @return
|
||||
// */
|
||||
// String cron();
|
||||
|
||||
boolean enabled() default true;
|
||||
// boolean enabled() default true;
|
||||
/**
|
||||
* 是否支持多机分布式运行
|
||||
* 若为false:每台机器都会执行一次
|
||||
@@ -36,5 +36,5 @@ public @interface XxzJob {
|
||||
*
|
||||
* @return
|
||||
*/
|
||||
boolean distributed() default true;
|
||||
boolean distributed() default false;
|
||||
}
|
||||
|
||||
@@ -0,0 +1,18 @@
|
||||
package com.xiang.core.quartz.api;
|
||||
|
||||
import com.xiang.core.quartz.model.JobConfigDO;
|
||||
import com.xiang.core.quartz.model.JobDefinition;
|
||||
|
||||
import java.util.List;
|
||||
|
||||
/**
|
||||
* @Author: xiang
|
||||
* @Date: 2026-01-06 15:10
|
||||
*/
|
||||
public interface AdminJobClient {
|
||||
|
||||
List<JobConfigDO> fetchJobByAppName(String appName, Long namespace);
|
||||
List<JobConfigDO> fetchJobByAppNameAndVersion(String appName, Integer version, Long namespace);
|
||||
|
||||
void registerJob(JobDefinition jobDefinition, String className);
|
||||
}
|
||||
@@ -0,0 +1,88 @@
|
||||
package com.xiang.core.quartz.api;
|
||||
|
||||
import com.alibaba.fastjson2.JSON;
|
||||
import com.alibaba.fastjson2.JSONObject;
|
||||
import com.google.common.collect.Lists;
|
||||
import com.google.common.collect.Maps;
|
||||
import com.xiang.core.quartz.model.JobConfigDO;
|
||||
import com.xiang.core.quartz.model.JobDefinition;
|
||||
import com.xiang.core.quartz.model.TaskRegisterRequest;
|
||||
import com.xiang.core.quartz.model.XxzJobProperties;
|
||||
import com.xiang.xmc.service.http.helper.BaseHttpHelp;
|
||||
import com.xiang.xmc.service.http.helper.HttpHelperFactory;
|
||||
import lombok.RequiredArgsConstructor;
|
||||
import org.apache.commons.lang3.StringUtils;
|
||||
import org.springframework.stereotype.Component;
|
||||
|
||||
import java.util.List;
|
||||
import java.util.Map;
|
||||
import java.util.Objects;
|
||||
|
||||
/**
|
||||
* @Author: xiang
|
||||
* @Date: 2026-01-06 15:11
|
||||
*/
|
||||
@Component
|
||||
@RequiredArgsConstructor
|
||||
public class HttpAdminJobClientImpl implements AdminJobClient {
|
||||
|
||||
private final XxzJobProperties xxzJobProperties;
|
||||
private static final BaseHttpHelp httpHelp = HttpHelperFactory.createQuartzHttp();
|
||||
|
||||
@Override
|
||||
public List<JobConfigDO> fetchJobByAppName(String appName, Long namespace) {
|
||||
String address = xxzJobProperties.getAdminAddress();
|
||||
address = address + "/open/quartz/fetch/list";
|
||||
Map<String, String> params = Maps.newHashMap();
|
||||
params.put("appName", appName);
|
||||
params.put("env", String.valueOf(namespace));
|
||||
String resp = httpHelp.doGet(address, params);
|
||||
if (StringUtils.isNotBlank(resp)) {
|
||||
JSONObject jsonObject = JSON.parseObject(resp);
|
||||
if (Objects.nonNull(jsonObject)) {
|
||||
String data = JSON.toJSONString(jsonObject.get("data"));
|
||||
if (StringUtils.isNotBlank(data)) {
|
||||
return JSON.parseArray(data, JobConfigDO.class);
|
||||
}
|
||||
}
|
||||
}
|
||||
return Lists.newArrayList();
|
||||
}
|
||||
|
||||
@Override
|
||||
public List<JobConfigDO> fetchJobByAppNameAndVersion(String appName, Integer version, Long namespace) {
|
||||
String address = xxzJobProperties.getAdminAddress();
|
||||
address = address + "/open/quartz/fetch/listByVersion";
|
||||
Map<String, String> params = Maps.newHashMap();
|
||||
params.put("appName", appName);
|
||||
params.put("env", String.valueOf(namespace));
|
||||
params.put("currVersion", String.valueOf(version));
|
||||
String resp = httpHelp.doGet(address, params);
|
||||
|
||||
if (StringUtils.isNotBlank(resp)) {
|
||||
JSONObject jsonObject = JSON.parseObject(resp);
|
||||
if (Objects.nonNull(jsonObject)) {
|
||||
String data = JSON.toJSONString(jsonObject.get("data"));
|
||||
if (StringUtils.isNotBlank(data)) {
|
||||
return JSON.parseArray(data, JobConfigDO.class);
|
||||
}
|
||||
}
|
||||
}
|
||||
return Lists.newArrayList();
|
||||
}
|
||||
|
||||
@Override
|
||||
public void registerJob(JobDefinition jobDefinition, String className) {
|
||||
TaskRegisterRequest request = new TaskRegisterRequest();
|
||||
request.setApplicationName(xxzJobProperties.getAppName());
|
||||
request.setApplicationAddress(xxzJobProperties.getAdminAddress());
|
||||
request.setBeanName(jobDefinition.getName());
|
||||
request.setCron(jobDefinition.getCron());
|
||||
request.setClazz(className);
|
||||
request.setMethod(jobDefinition.getMethod().getName());
|
||||
request.setEnv(xxzJobProperties.getNamespace());
|
||||
String address = xxzJobProperties.getAdminAddress();
|
||||
address = address + "/open/quartz/register/single";
|
||||
httpHelp.doPost(address, JSON.toJSONString(request));
|
||||
}
|
||||
}
|
||||
@@ -1,14 +1,22 @@
|
||||
package com.xiang.core.quartz.boostrap;
|
||||
|
||||
import com.xiang.core.quartz.api.AdminJobClient;
|
||||
import com.xiang.core.quartz.holder.JobDefinitionHolder;
|
||||
import com.xiang.core.quartz.model.JobDefinition;
|
||||
import com.xiang.core.quartz.model.JobConfigDO;
|
||||
import com.xiang.core.quartz.model.XxzJobProperties;
|
||||
import com.xiang.core.quartz.schedule.JobScheduler;
|
||||
import lombok.extern.slf4j.Slf4j;
|
||||
import org.apache.commons.collections4.CollectionUtils;
|
||||
import org.springframework.beans.factory.annotation.Autowired;
|
||||
import org.springframework.boot.ApplicationArguments;
|
||||
import org.springframework.boot.ApplicationRunner;
|
||||
import org.springframework.stereotype.Component;
|
||||
|
||||
import java.util.List;
|
||||
import java.util.Map;
|
||||
import java.util.function.Function;
|
||||
import java.util.stream.Collectors;
|
||||
|
||||
/**
|
||||
* @Author: xiang
|
||||
* @Date: 2026-01-06 09:50
|
||||
@@ -19,13 +27,30 @@ public class JobBootstrap implements ApplicationRunner {
|
||||
|
||||
@Autowired
|
||||
private JobScheduler scheduler;
|
||||
@Autowired
|
||||
private AdminJobClient adminJobClient;
|
||||
@Autowired
|
||||
private XxzJobProperties xxzJobProperties;
|
||||
|
||||
@Override
|
||||
public void run(ApplicationArguments args) {
|
||||
// 启动时动态获取此app下面的数据库配置好的定时任务 用于管理cron和开关
|
||||
List<JobConfigDO> jobConfigDOS = adminJobClient.fetchJobByAppName(xxzJobProperties.getAppName(), xxzJobProperties.getNamespace());
|
||||
if (CollectionUtils.isEmpty(jobConfigDOS)) {
|
||||
return;
|
||||
}
|
||||
Map<String, JobConfigDO> map = jobConfigDOS.stream().collect(Collectors.toMap(JobConfigDO::getBeanName, Function.identity(), (a, b) -> a));
|
||||
JobDefinitionHolder.getAll()
|
||||
.stream()
|
||||
.filter(JobDefinition::isEnabled)
|
||||
.forEach(scheduler::schedule);
|
||||
.forEach(item -> {
|
||||
if (map.containsKey(item.getName())) {
|
||||
JobConfigDO jobConfigDO = map.get(item.getName());
|
||||
if (jobConfigDO.getJobSwitch() == 1) {
|
||||
item.setCron(jobConfigDO.getCron());
|
||||
item.setEnabled(jobConfigDO.getJobSwitch() == 1);
|
||||
scheduler.schedule(item);
|
||||
}
|
||||
}
|
||||
});
|
||||
}
|
||||
}
|
||||
|
||||
|
||||
@@ -2,11 +2,15 @@ package com.xiang.core.quartz.config;
|
||||
|
||||
import com.xiang.core.quartz.executor.JobExecutor;
|
||||
import com.xiang.core.quartz.model.XxzJobProperties;
|
||||
import com.xiang.core.quartz.trigger.JobTrigger;
|
||||
import com.xiang.core.quartz.trigger.TriggerRoute;
|
||||
import org.springframework.boot.context.properties.EnableConfigurationProperties;
|
||||
import org.springframework.context.annotation.Bean;
|
||||
import org.springframework.context.annotation.Configuration;
|
||||
import org.springframework.scheduling.annotation.EnableScheduling;
|
||||
|
||||
import java.util.List;
|
||||
|
||||
/**
|
||||
* @Author: xiang
|
||||
* @Date: 2026-01-06 09:29
|
||||
@@ -20,4 +24,9 @@ public class XxzJobAutoConfiguration {
|
||||
public JobExecutor jobExecutor() {
|
||||
return new JobExecutor();
|
||||
}
|
||||
|
||||
@Bean
|
||||
public TriggerRoute triggerRoute(List<JobTrigger> triggers) {
|
||||
return new TriggerRoute(triggers);
|
||||
}
|
||||
}
|
||||
|
||||
@@ -15,16 +15,15 @@ import org.springframework.stereotype.Component;
|
||||
public class JobExecutor {
|
||||
|
||||
private static final Logger log = LoggerFactory.getLogger(JobExecutor.class);
|
||||
|
||||
/**
|
||||
* v1版本 本地反射调用
|
||||
* @param jobDefinition
|
||||
* @param job
|
||||
*/
|
||||
public void executor(JobDefinition jobDefinition) {
|
||||
public void executor(JobDefinition job) {
|
||||
try {
|
||||
jobDefinition.getMethod().invoke(jobDefinition.getBean());
|
||||
job.getMethod().invoke(job.getBean());
|
||||
} catch (Exception e) {
|
||||
log.error("xxz-job execute error, job={}", jobDefinition.getName(), e);
|
||||
log.error("xxz-job execute error, job={}", job.getName(), e);
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
@@ -30,13 +30,6 @@ public class JobDefinitionHolder {
|
||||
public static JobDefinition getOne(String name) {
|
||||
return MAP.get(name);
|
||||
}
|
||||
|
||||
public static void updateOne(JobDefinition jobDefinition) {
|
||||
if (MAP.containsKey(jobDefinition.getName())) {
|
||||
MAP.put(jobDefinition.getName(), jobDefinition);
|
||||
}
|
||||
}
|
||||
|
||||
public static void delOne(JobDefinition jobDefinition) {
|
||||
MAP.remove(jobDefinition.getName());
|
||||
}
|
||||
|
||||
@@ -0,0 +1,84 @@
|
||||
package com.xiang.core.quartz.model;
|
||||
|
||||
import com.baomidou.mybatisplus.annotation.TableName;
|
||||
import lombok.AllArgsConstructor;
|
||||
import lombok.Data;
|
||||
import lombok.NoArgsConstructor;
|
||||
|
||||
import java.io.Serial;
|
||||
import java.io.Serializable;
|
||||
import java.time.LocalDateTime;
|
||||
|
||||
/**
|
||||
* @Author: xiang
|
||||
* @Date: 2025-12-30 09:42
|
||||
*/
|
||||
@Data
|
||||
@AllArgsConstructor
|
||||
@NoArgsConstructor
|
||||
@TableName("xmc_quartz_config")
|
||||
public class JobConfigDO implements Serializable {
|
||||
|
||||
@Serial
|
||||
private static final long serialVersionUID = 1L;
|
||||
|
||||
/**
|
||||
* id
|
||||
*/
|
||||
private Long id;
|
||||
/**
|
||||
* 应用名称
|
||||
*/
|
||||
private String applicationName;
|
||||
|
||||
/**
|
||||
* 应用地址
|
||||
*/
|
||||
private String applicationAddress;
|
||||
|
||||
/**
|
||||
* 定时任务名称
|
||||
*/
|
||||
private String beanName;
|
||||
|
||||
/**
|
||||
* 任务执行调度时间
|
||||
*/
|
||||
private String cron;
|
||||
|
||||
/**
|
||||
* 类名
|
||||
*/
|
||||
private String clazz;
|
||||
|
||||
/**
|
||||
* 方法
|
||||
*/
|
||||
private String method;
|
||||
|
||||
/**
|
||||
* 任务开关
|
||||
* 0:关闭 1:开启
|
||||
*/
|
||||
private Integer jobSwitch;
|
||||
|
||||
/**
|
||||
* 删除标识(0:未删除 1:已删除)
|
||||
*/
|
||||
private Integer delFlag;
|
||||
|
||||
/**
|
||||
* 创建时间
|
||||
*/
|
||||
private LocalDateTime createTime;
|
||||
|
||||
/**
|
||||
* 修改时间
|
||||
*/
|
||||
private LocalDateTime updateTime;
|
||||
|
||||
/**
|
||||
* 上次执行时间
|
||||
*/
|
||||
private LocalDateTime lastRunningTime;
|
||||
}
|
||||
@@ -0,0 +1,50 @@
|
||||
package com.xiang.core.quartz.model;
|
||||
|
||||
import lombok.AllArgsConstructor;
|
||||
import lombok.Data;
|
||||
import lombok.NoArgsConstructor;
|
||||
|
||||
/**
|
||||
* @Author: xiang
|
||||
* @Date: 2026-01-05 15:49
|
||||
*/
|
||||
@Data
|
||||
@AllArgsConstructor
|
||||
@NoArgsConstructor
|
||||
public class TaskRegisterRequest {
|
||||
|
||||
/**
|
||||
* 应用名称
|
||||
*/
|
||||
private String applicationName;
|
||||
|
||||
/**
|
||||
* 应用地址
|
||||
*/
|
||||
private String applicationAddress;
|
||||
|
||||
/**
|
||||
* 定时任务名称
|
||||
*/
|
||||
private String beanName;
|
||||
|
||||
/**
|
||||
* 任务执行调度时间
|
||||
*/
|
||||
private String cron;
|
||||
|
||||
/**
|
||||
* 类名
|
||||
*/
|
||||
private String clazz;
|
||||
|
||||
/**
|
||||
* 方法
|
||||
*/
|
||||
private String method;
|
||||
|
||||
/**
|
||||
* 环境
|
||||
*/
|
||||
private Long env;
|
||||
}
|
||||
@@ -20,4 +20,14 @@ public class XxzJobProperties {
|
||||
* DB刷新任务间隔(毫秒)
|
||||
*/
|
||||
private int refreshInterval = 5000;
|
||||
|
||||
/**
|
||||
* 调度中心地址
|
||||
*/
|
||||
private String adminAddress;
|
||||
|
||||
/**
|
||||
* 命名空间
|
||||
*/
|
||||
private Long namespace;
|
||||
}
|
||||
|
||||
@@ -1,6 +1,7 @@
|
||||
package com.xiang.core.quartz.scanner;
|
||||
|
||||
import com.xiang.core.quartz.annotation.XxzJob;
|
||||
import com.xiang.core.quartz.api.AdminJobClient;
|
||||
import com.xiang.core.quartz.holder.JobDefinitionHolder;
|
||||
import com.xiang.core.quartz.model.JobDefinition;
|
||||
import lombok.extern.slf4j.Slf4j;
|
||||
@@ -26,6 +27,8 @@ public class JobScanner implements SmartInitializingSingleton {
|
||||
|
||||
@Autowired
|
||||
private ApplicationContext applicationContext;
|
||||
@Autowired
|
||||
private AdminJobClient adminJobClient;
|
||||
|
||||
@Override
|
||||
public void afterSingletonsInstantiated() {
|
||||
@@ -50,9 +53,8 @@ public class JobScanner implements SmartInitializingSingleton {
|
||||
job.setDistributed(xxzJob.distributed());
|
||||
job.setBean(bean);
|
||||
job.setMethod(method);
|
||||
job.setEnabled(xxzJob.enabled());
|
||||
job.setCron(xxzJob.cron());
|
||||
JobDefinitionHolder.register(job);
|
||||
adminJobClient.registerJob(job, method.getClass().getName());
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
@@ -0,0 +1,38 @@
|
||||
package com.xiang.core.quartz.schedule;
|
||||
|
||||
import com.xiang.core.quartz.api.AdminJobClient;
|
||||
import com.xiang.core.quartz.holder.JobDefinitionHolder;
|
||||
import com.xiang.core.quartz.model.JobConfigDO;
|
||||
import com.xiang.core.quartz.model.JobDefinition;
|
||||
import com.xiang.core.quartz.model.XxzJobProperties;
|
||||
import org.springframework.beans.factory.annotation.Autowired;
|
||||
import org.springframework.scheduling.annotation.Scheduled;
|
||||
import org.springframework.stereotype.Component;
|
||||
|
||||
import java.util.List;
|
||||
|
||||
/**
|
||||
* @Author: xiang
|
||||
* @Date: 2026-01-06 15:59
|
||||
*/
|
||||
@Component
|
||||
public class JobConfigRefreshTask {
|
||||
|
||||
@Autowired
|
||||
private AdminJobClient adminJobClient;
|
||||
@Autowired
|
||||
private XxzJobProperties xxzJobProperties;
|
||||
@Autowired
|
||||
private JobScheduler jobScheduler;
|
||||
@Scheduled(fixedDelay = 5000)
|
||||
public void refresh() {
|
||||
List<JobConfigDO> jobConfigDOS = adminJobClient.fetchJobByAppName(xxzJobProperties.getAppName(), xxzJobProperties.getNamespace());
|
||||
|
||||
for (JobConfigDO jobConfigDO : jobConfigDOS) {
|
||||
JobDefinition jobDefinition = JobDefinitionHolder.getOne(jobConfigDO.getBeanName());
|
||||
jobScheduler.refresh(jobDefinition, jobConfigDO);
|
||||
}
|
||||
}
|
||||
|
||||
|
||||
}
|
||||
@@ -1,12 +1,19 @@
|
||||
package com.xiang.core.quartz.schedule;
|
||||
|
||||
import com.xiang.core.quartz.executor.JobExecutor;
|
||||
import com.google.common.collect.Maps;
|
||||
import com.xiang.core.quartz.model.JobConfigDO;
|
||||
import com.xiang.core.quartz.model.JobDefinition;
|
||||
import com.xiang.core.quartz.trigger.TriggerRoute;
|
||||
import lombok.RequiredArgsConstructor;
|
||||
import org.apache.commons.lang3.StringUtils;
|
||||
import org.springframework.scheduling.TaskScheduler;
|
||||
import org.springframework.scheduling.support.CronTrigger;
|
||||
import org.springframework.stereotype.Component;
|
||||
|
||||
import java.util.Map;
|
||||
import java.util.Objects;
|
||||
import java.util.concurrent.ScheduledFuture;
|
||||
|
||||
/**
|
||||
* @Author: xiang
|
||||
* @Date: 2026-01-06 09:47
|
||||
@@ -15,12 +22,50 @@ import org.springframework.stereotype.Component;
|
||||
@RequiredArgsConstructor
|
||||
public class JobScheduler {
|
||||
private final TaskScheduler taskScheduler;
|
||||
private final JobExecutor jobExecutor;
|
||||
private final TriggerRoute triggerRoute;
|
||||
private final Map<String, ScheduledFuture<?>> scheduledTasks = Maps.newConcurrentMap();
|
||||
|
||||
public void schedule(JobDefinition job) {
|
||||
taskScheduler.schedule(
|
||||
() -> jobExecutor.executor(job),
|
||||
public ScheduledFuture<?> schedule(JobDefinition job) {
|
||||
return taskScheduler.schedule(
|
||||
() -> triggerRoute.route(job).trigger(job),
|
||||
new CronTrigger(job.getCron())
|
||||
);
|
||||
}
|
||||
|
||||
public synchronized void refresh(JobDefinition job, JobConfigDO cfg) {
|
||||
String jobName = job.getName();
|
||||
|
||||
// 1️⃣ 未配置 or 未启用 → 停止
|
||||
if (Objects.isNull(cfg) || Objects.equals(cfg.getJobSwitch(), 0)) {
|
||||
job.setCron(null);
|
||||
cancel(job);
|
||||
return;
|
||||
}
|
||||
|
||||
String newCron = cfg.getCron();
|
||||
String oldCron = job.getCron();
|
||||
|
||||
// 2️⃣ cron 未变 & 已存在 → 不动
|
||||
if (scheduledTasks.containsKey(jobName) && StringUtils.equals(newCron, oldCron)) {
|
||||
return;
|
||||
}
|
||||
|
||||
// 3️⃣ 先取消旧任务
|
||||
cancel(job);
|
||||
// 4️⃣ 创建新任务
|
||||
job.setCron(newCron);
|
||||
job.setEnabled(true);
|
||||
ScheduledFuture<?> future = this.schedule(job);
|
||||
scheduledTasks.put(jobName, future);
|
||||
|
||||
}
|
||||
|
||||
private void cancel(JobDefinition job) {
|
||||
ScheduledFuture<?> future = scheduledTasks.remove(job.getName());
|
||||
if (future != null) {
|
||||
// false 不中断当前任务,等待任务完成
|
||||
future.cancel(true);
|
||||
triggerRoute.route(job).cancel(job.getName());
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
@@ -0,0 +1,61 @@
|
||||
package com.xiang.core.quartz.trigger;
|
||||
|
||||
import com.xiang.core.quartz.executor.JobExecutor;
|
||||
import com.xiang.core.quartz.model.JobDefinition;
|
||||
import com.xiang.core.quartz.model.XxzJobProperties;
|
||||
import lombok.RequiredArgsConstructor;
|
||||
import lombok.extern.slf4j.Slf4j;
|
||||
import org.apache.commons.lang3.StringUtils;
|
||||
import org.redisson.api.RLock;
|
||||
import org.redisson.api.RedissonClient;
|
||||
import org.springframework.stereotype.Component;
|
||||
|
||||
/**
|
||||
* @Author: xiang
|
||||
* @Date: 2026-01-07 09:33
|
||||
*/
|
||||
@Slf4j
|
||||
@Component
|
||||
@RequiredArgsConstructor
|
||||
public class DistributeJobTrigger implements JobTrigger {
|
||||
|
||||
private final RedissonClient redissonClient;
|
||||
private final JobExecutor jobExecutor;
|
||||
private final XxzJobProperties xxzJobProperties;
|
||||
|
||||
@Override
|
||||
public void trigger(JobDefinition jobDefinition) {
|
||||
if (!jobDefinition.isEnabled() || StringUtils.isEmpty(jobDefinition.getCron())) {
|
||||
log.info("任务:{}已关闭,无需执行!", jobDefinition.getName());
|
||||
return;
|
||||
}
|
||||
// 校验是否支持分布式,这里暂时忽略,先支持单机进行
|
||||
String key = "xxzJob:" + xxzJobProperties.getAppName() + jobDefinition.getName();
|
||||
RLock lock = redissonClient.getLock(key);
|
||||
boolean flag = lock.tryLock();
|
||||
try {
|
||||
if (flag) {
|
||||
jobExecutor.executor(jobDefinition);
|
||||
} else {
|
||||
log.info("其他实例正在执行任务!");
|
||||
}
|
||||
} catch (Exception e) {
|
||||
log.info("xxz-Job:{}获取锁失败", jobDefinition.getName());
|
||||
} finally {
|
||||
// 释放锁
|
||||
if (flag && lock.isHeldByCurrentThread()) {
|
||||
lock.unlock();
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
@Override
|
||||
public void cancel(String jobName) {
|
||||
|
||||
}
|
||||
|
||||
@Override
|
||||
public TriggerType type() {
|
||||
return TriggerType.DISTRIBUTE;
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,16 @@
|
||||
package com.xiang.core.quartz.trigger;
|
||||
|
||||
import com.xiang.core.quartz.model.JobDefinition;
|
||||
|
||||
/**
|
||||
* @Author: xiang
|
||||
* @Date: 2026-01-07 09:27
|
||||
*/
|
||||
public interface JobTrigger {
|
||||
|
||||
void trigger(JobDefinition jobDefinition);
|
||||
|
||||
void cancel(String jobName);
|
||||
|
||||
TriggerType type();
|
||||
}
|
||||
@@ -0,0 +1,57 @@
|
||||
package com.xiang.core.quartz.trigger;
|
||||
|
||||
import com.xiang.core.quartz.executor.JobExecutor;
|
||||
import com.xiang.core.quartz.model.JobDefinition;
|
||||
import lombok.RequiredArgsConstructor;
|
||||
import lombok.extern.slf4j.Slf4j;
|
||||
import org.springframework.stereotype.Component;
|
||||
|
||||
import java.util.concurrent.ConcurrentHashMap;
|
||||
import java.util.concurrent.atomic.AtomicBoolean;
|
||||
|
||||
/**
|
||||
* @Author: xiang
|
||||
* @Date: 2026-01-07 09:28
|
||||
*/
|
||||
@Slf4j
|
||||
@Component
|
||||
@RequiredArgsConstructor
|
||||
public class LocalJobTrigger implements JobTrigger {
|
||||
|
||||
private final JobExecutor jobExecutor;
|
||||
private final ConcurrentHashMap<String, AtomicBoolean> running = new ConcurrentHashMap<>();
|
||||
@Override
|
||||
public void trigger(JobDefinition job) {
|
||||
if (!job.isEnabled()) {
|
||||
// log.info("job {} disabled, skip execution", job.getName());
|
||||
return;
|
||||
}
|
||||
|
||||
AtomicBoolean flag = running.computeIfAbsent(
|
||||
job.getName(), k -> new AtomicBoolean(false)
|
||||
);
|
||||
|
||||
if (!flag.compareAndSet(false, true)) {
|
||||
// log.warn("job {} is already running, skip", job.getName());
|
||||
return;
|
||||
}
|
||||
|
||||
try {
|
||||
jobExecutor.executor(job);
|
||||
} catch (Exception e) {
|
||||
log.error("xxz-job execute error, job={}", job.getName(), e);
|
||||
} finally {
|
||||
flag.set(false);
|
||||
}
|
||||
}
|
||||
|
||||
@Override
|
||||
public void cancel(String jobName) {
|
||||
running.remove(jobName);
|
||||
}
|
||||
|
||||
@Override
|
||||
public TriggerType type() {
|
||||
return TriggerType.LOCAL;
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,29 @@
|
||||
package com.xiang.core.quartz.trigger;
|
||||
|
||||
import com.xiang.core.quartz.model.JobDefinition;
|
||||
|
||||
import java.util.EnumMap;
|
||||
import java.util.List;
|
||||
import java.util.Map;
|
||||
|
||||
/**
|
||||
* @Author: xiang
|
||||
* @Date: 2026-01-07 09:48
|
||||
*/
|
||||
public class TriggerRoute {
|
||||
|
||||
private final Map<TriggerType, JobTrigger> triggerMap;
|
||||
|
||||
public TriggerRoute(List<JobTrigger> triggers) {
|
||||
triggerMap = new EnumMap<>(TriggerType.class);
|
||||
for (JobTrigger trigger : triggers) {
|
||||
triggerMap.put(trigger.type(), trigger);
|
||||
}
|
||||
}
|
||||
|
||||
public JobTrigger route(JobDefinition job) {
|
||||
return job.isDistributed()
|
||||
? triggerMap.get(TriggerType.DISTRIBUTE)
|
||||
: triggerMap.get(TriggerType.LOCAL);
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,19 @@
|
||||
package com.xiang.core.quartz.trigger;
|
||||
|
||||
import lombok.Getter;
|
||||
import lombok.RequiredArgsConstructor;
|
||||
|
||||
/**
|
||||
* @Author: xiang
|
||||
* @Date: 2026-01-07 09:46
|
||||
*/
|
||||
@Getter
|
||||
@RequiredArgsConstructor
|
||||
public enum TriggerType {
|
||||
|
||||
LOCAL("单机"),
|
||||
DISTRIBUTE("分布式"),
|
||||
|
||||
;
|
||||
private final String desc;
|
||||
}
|
||||
@@ -22,7 +22,7 @@
|
||||
<dependency>
|
||||
<groupId>com.xiang.starter</groupId>
|
||||
<artifactId>xservice-quartz-core</artifactId>
|
||||
<version>1.0-SNAPSHOT</version>
|
||||
<version>1.1</version>
|
||||
</dependency>
|
||||
|
||||
<dependency>
|
||||
|
||||
@@ -12,7 +12,7 @@ import org.springframework.stereotype.Component;
|
||||
@Component
|
||||
public class TestXxzJob1 {
|
||||
|
||||
@XxzJob(name = "TestXxzJob", cron = "0/1 * * * * ? ", enabled = true)
|
||||
@XxzJob(name = "TestXxzJob")
|
||||
public void test() {
|
||||
log.info("任务调度开始");
|
||||
}
|
||||
|
||||
@@ -1,5 +1,7 @@
|
||||
xxz-job:
|
||||
app-name: springboot-quartz-test
|
||||
admin-address: http://127.0.0.1:30030
|
||||
namespace: 1
|
||||
|
||||
spring:
|
||||
main:
|
||||
|
||||
Reference in New Issue
Block a user