xxl-job的使用
1 配置服务
按照调度器
- 运行服务
- 配置执行器
- 配置bean
2 运行服务
<dependency>
<groupId>com.xuxueli</groupId>
<artifactId>xxl-job-core</artifactId>
<version>${xxl-job-core.verion}</version>
</dependency>
配置
···
@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;
}
}
···
定时任务
@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;
}
}
调用服务代码
@Slf4j
@Api(tags={"用户接口"})
@RestController
public class UserController {
@Autowired
XxlCron xxlCron;
@GetMapping("/info")
public String configInfo2() {
return xxlCron.getCurrentTime();
}
}