xxl-job的使用
1 配置服务
按照调度器
https://www.xuxueli.com/xxl-job/#2.1 初始化“调度数据库”
- 运行服务
- 配置执行器
- 配置bean
2 运行服务
代码语言:txt复制 <dependency>
<groupId>com.xuxueli</groupId>
<artifactId>xxl-job-core</artifactId>
<version>${xxl-job-core.verion}</version>
</dependency>
配置
代码语言:txt复制@Configuration
public class XxlJobConfig {
private Logger logger = LoggerFactory.getLogger(XxlJobConfig.class);
@Value("${xxl.job.admin.addresses}")
private String adminAddresses;
@Value("${xxl.job.accessToken}")
private String accessToken;
@Value("${xxl.job.executor.appname}")
private String appname;
@Value("${xxl.job.executor.address}")
private String address;
@Value("${xxl.job.executor.ip}")
private String ip;
@Value("${xxl.job.executor.port}")
private int port;
@Value("${xxl.job.executor.logpath}")
private String logPath;
@Value("${xxl.job.executor.logretentiondays}")
private int logRetentionDays;
@Bean
public XxlJobSpringExecutor xxlJobExecutor() {
logger.info(">>>>>>>>>>> xxl-job config init.");
XxlJobSpringExecutor xxlJobSpringExecutor = new XxlJobSpringExecutor();
xxlJobSpringExecutor.setAdminAddresses(adminAddresses);
xxlJobSpringExecutor.setAppname(appname);
xxlJobSpringExecutor.setAddress(address);
xxlJobSpringExecutor.setIp(ip);
xxlJobSpringExecutor.setPort(port);
xxlJobSpringExecutor.setAccessToken(accessToken);
xxlJobSpringExecutor.setLogPath(logPath);
xxlJobSpringExecutor.setLogRetentionDays(logRetentionDays);
return xxlJobSpringExecutor;
}
}
定时任务
代码语言:txt复制@Data
@Slf4j
@Component
public class XxlCron {
private static final String FORMAT_STR_TIME = "yyyy-MM-dd HH:mm:ss";
private String currentTime = "";
public static String getCurrentDateSimpleTpl() {
return getCurrentDateSimpleTpl(FORMAT_STR_TIME, System.currentTimeMillis()/1000);
}
private static String getCurrentDateSimpleTpl(String tpl, long timestamp) {
LocalDateTime localDateTime = LocalDateTime.ofEpochSecond(timestamp, 0, ZoneOffset.ofHours(8));
DateTimeFormatter formatter2 = DateTimeFormatter.ofPattern(tpl);
return localDateTime.format(formatter2);
}
@XxlJob("testRunXxl")
public ReturnT<String> execute() {
XxlJobHelper.log("XXL-JOB testRunXxl start");
String currentTime = getCurrentDateSimpleTpl();
log.info("currentTime:" currentTime);
this.currentTime = currentTime;
return ReturnT.SUCCESS;
}
}
调用服务代码
代码语言:txt复制@Slf4j
@Api(tags={"用户接口"})
@RestController
public class UserController {
@Autowired
XxlCron xxlCron;
@GetMapping("/info")
public String configInfo2() {
return xxlCron.getCurrentTime();
}
}
运行服务
http://127.0.0.1:7190/info
具体代码看这个即可:
https://github.com/beckbikang/spring-cloud/tree/main/kcron/kxxljob