文章目录
- 3.SpringBoot整合xxl-job
- 3.1定时任务服务配置
- 3.1.1导入maven依赖
- 3.1.2yml配置
- 3.1.3XxlJobConfig配置类
- 3.1.4定时任务类
- 3.2xxl-job配置
- 3.2.1新增执行器
- 3.2.2新增任务
- 3.2.3执行任务
- 3.2.4查看日志
- 3.2.5查看任务后台日志
- 3.3小结
3.SpringBoot整合xxl-job
3.1定时任务服务配置
3.1.1导入maven依赖
- xxl-job服务和该定时任务服务必须在本地,或者在服务器端
<!-- xxl-job-core -->
<dependency><groupId>com.xuxueli</groupId><artifactId>xxl-job-core</artifactId><version>2.3.1</version>
</dependency>
3.1.2yml配置
xxl:job:admin:addresses: http://localhost:8080/xxl-job-adminaccessToken: default_token #和xxl-job服务里的accessToken保持一致executor:# 执行器名称appname: easpan-file-job#ip: 10.123.1.53port: 9999# 日志地址logpath: /data/applogs/xxl-job/jobhandler# 日志保存时间logretentiondays: 30
3.1.3XxlJobConfig配置类
@Configuration
@Slf4j
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(initMethod = "start", destroyMethod = "destroy")public XxlJobSpringExecutor xxlJobExecutor() {log.info(">>>>>>>>>>> xxl-job config init.");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;}}
3.1.4定时任务类
@Component
public class CleanDeletedFilesJob {@XxlJob("CleanDeletedFilesJob")public ReturnT<String> CleanDeletedFilesJob() throws InterruptedException {XxlJobHelper.log("定时任务开始");System.out.println(new Date().toString() + "定时任务开始");String param = XxlJobHelper.getJobParam();System.out.println(param);for (int i = 0; i < 5; i++) {System.out.println(new Date().toString()+"XXL-JOB, Hello World");XxlJobHelper.log("beat at:" + i);TimeUnit.SECONDS.sleep(2);}System.out.println("测试完成!!!!!!!!!!!!!!!!!!!!!!!!!!!!");XxlJobHelper.log(new Date().toString() + "定时任务结束");return ReturnT.SUCCESS;}
}
3.2xxl-job配置
3.2.1新增执行器
- 填写执行器名称;
- 注意:选择自动注册方式
- 一个小bug:若选择手动录入
- 填写地址(127.0.0.1:9999 )均会报500错误(xxl-job版本过高原因导致)
- 填写地址(http://127.0.0.1:9999/、http://ip地址:9999/)就不会报错,正常运行
或:
3.2.2新增任务
- 选择刚刚创建的执行器
- 填写调度类型(任务执行时间)
- JobHandler(即为定时任务类中 @XxlJob的值)
3.2.3执行任务
3.2.4查看日志
- 详细日志
3.2.5查看任务后台日志
3.3小结
- 定时任务配置步骤
- 导入maven依赖
- yml配置(注意accessToken的配置)
- 创建XxlConfig配置类
- 创建定时任务类,编写定时任务逻辑
- xxl-job配置
- 新增执行器(执行器名称、注册地址)
- 新增任务(JobHandler与@XxlJob的value值一致、填写调度时间)
- 执行任务(一次/运行)