一、分布式定时任务
xxl-job是分布式任务调度的平台,可以在图形界面操作,解决分布式的定时任务的重复执行,不能直接修改定时设置等
参考地址:
https://www.xuxueli.com/xxl-job/
二、使用步骤
1.pom文件
<parent>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-parent</artifactId>
<version>2.4.2</version>
</parent>
<groupId>org.example.test</groupId>
<artifactId>xxl-job-test</artifactId>
<version>1.0-SNAPSHOT</version>
<dependencies>
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-web</artifactId>
</dependency>
<!-- https://mvnrepository.com/artifact/com.xuxueli/xxl-job-core -->
<dependency>
<groupId>com.xuxueli</groupId>
<artifactId>xxl-job-core</artifactId>
<version>2.3.0</version>
</dependency>
2.application.yml
server:
port: 8093
xxl:
job:
admin:
addresses: http://127.0.0.1:8080/xxl-job-admin #调度中心地址
accessToken: #执行器通讯token
executor:
appname: springboot-xxl-job #执行器名称,执行器心跳注册分组依据,为空时关闭自动注册
address: #执行器注册地址
ip: #执行器IP
port: 9999 #执行器端口号
logpath: /data/applogs/xxl-job/jobhandler #执行器运行日志文件存储路径
logretentiondays: 30 #日志文件保存天数
3.configuration配置
package com.test.configure;
import com.xxl.job.core.executor.impl.XxlJobSpringExecutor;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
@Configuration
public class XXlJobConfig {
@Value("${xxl.job.admin.addresses}")
private String adminAddresses;
@Value("${xxl.job.executor.appname}")
private String appName;
@Value("${xxl.job.executor.ip}")
private String ip;
@Value("${xxl.job.executor.port}")
private int port;
@Value("${xxl.job.accessToken}")
private String accessToken;
@Value("${xxl.job.executor.logpath}")
private String logPath;
@Value("${xxl.job.executor.logretentiondays}")
private int logRetentionDays;
@Bean
public XxlJobSpringExecutor xxlJobExecutor() {
XxlJobSpringExecutor xxlJobSpringExecutor = new XxlJobSpringExecutor();
xxlJobSpringExecutor.setAdminAddresses(adminAddresses);
xxlJobSpringExecutor.setAppname(appName);
xxlJobSpringExecutor.setIp(ip);
xxlJobSpringExecutor.setPort(port);
xxlJobSpringExecutor.setAccessToken(accessToken);
xxlJobSpringExecutor.setLogPath(logPath);
xxlJobSpringExecutor.setLogRetentionDays(logRetentionDays);
return xxlJobSpringExecutor;
}
}
4.定时任务逻辑处理
package com.test.jobhandler;
import com.xxl.job.core.context.XxlJobHelper;
import com.xxl.job.core.handler.annotation.XxlJob;
import org.springframework.stereotype.Component;
@Component
public class TestJobHandler {
@XxlJob("testJobHandler")
public void testJobHandler() throws Exception {
XxlJobHelper.log("XXL-JOB, Hello World.");
for (int i = 0; i < 5; i++) {
XxlJobHelper.log("beat at:" + i);
System.out.println(i);
}
// default success
}
}
总结
以上是bean模式的使用,其他模式使用可以详见官方文档,
控制台需要自行下载xxl-job-amin
参考地址:
https://www.xuxueli.com/xxl-job/