1.在想要不要介绍呢,哈哈哈哈
2.下面我们正式开始
2.1 首先XXL-JOB的官网地址是:https://www.xuxueli.com/xxl-job/,可以去看看官方文档,比较更加的清楚。
2.2 我们需要下载XXL-JOB的源码,下载地址是:
| https://github.com/xuxueli/xxl-job | Download |
| http://gitee.com/xuxueli0323/xxl-job | Download |
2.3 环境支持:
Maven3+
Jdk1.8+
Mysql5.7+
2.4 初始化“调度数据库”
下载好XXL-JOB的源码,解压这个项目源码,并获取“调度数据库初始化SQL脚本”,到mysql里面运行sql脚本文件,“调度数据库SQL脚本”位置是:/xxl-job/doc/db/tables_xxl_job.sql
2.5 项目源码结构:
2.6 配置部署“调度中心”:
2.7 项目使用XXL-JOB步骤:
xxl:
job:
admin:
addresses: http://localhost:8080/xxl-job-admin/jobinfo #任务管理器地址
userName: admin #账户
password: 123456 #密码
ifRemember: on #
executor:
appname: xxl-job-executor-sample #执行器的AppName名字
ip: ""#默认为空
port: 9999
logpath: data/applogs/xxl-job/jobhandler
accessToken: 1111 #验证,在调度中心中设置了,所以这边也要设置,必须一样
logretentiondays: 30
address:
#注意:配置执行器的名称、IP地址、端口号,后面如果配置多个执行器时,要防止端口冲突
import com.xxl.job.core.executor.impl.XxlJobSpringExecutor;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
/**
* xxl-job config
*
* @author xuxueli 2017-04-28
*/
@Configuration
public class XxlJobConfig {
private Logger logger = LoggerFactory.getLogger(XxlJobConfig.class);
@Value("${xxl.job.admin.addresses}")
private String adminAddresses;
@Value("${xxl.job.executor.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;
}
}
/**
* 针对多网卡、容器内部署等情况,可借助 "spring-cloud-commons" 提供的 "InetUtils" 组件灵活定制注册IP;
*
* 1、引入依赖:
* <dependency>
* <groupId>org.springframework.cloud</groupId>
* <artifactId>spring-cloud-commons</artifactId>
* <version>${version}</version>
* </dependency>
*
* 2、配置文件,或者容器启动变量
* spring.cloud.inetutils.preferred-networks: 'xxx.xxx.xxx.'
*
* 3、获取IP
* String ip_ = inetUtils.findFirstNonLoopbackHostInfo().getIpAddress();
*/
import com.xxl.job.core.biz.model.ReturnT;
import com.xxl.job.core.handler.annotation.XxlJob;
import groovy.util.logging.Slf4j;
import org.springframework.stereotype.Component;
@Component
@Slf4j
public class TestHandler {
//calendarTest这个名字是你在添加定时任务的时候所需要的,他相当于指定这个定时任务执行的是哪一个
@XxlJob("calendarTest")
public ReturnT<String> calendarTest(String param) throws Exception {
//输出你所传的值
System.out.println(param);
return ReturnT.SUCCESS;
}
}
private String cookie;
//你部署的调度中心接口地址
private String url = "http://localhost:8080/xxl-job-admin/jobinfo";
//账户
private String userName = "admin";
//密码
private String password = "123456";
//
private String ifRemember = "on";
//执行器的id
private int jobGroup = 1;
//ps:或者你可以把这些放到配置文件中
/**
* 登录
* @return
*/
private String getCookie() {
String path = url + "/login";
Map<String, Object> hashMap = new HashMap();
hashMap.put("userName", userName);
hashMap.put("password", password);
hashMap.put("ifRemember", ifRemember);
HttpResponse response = HttpRequest.post(path).form(hashMap).execute();
List<HttpCookie> cookies = response.getCookies();
StringBuilder sb = new StringBuilder();
for (HttpCookie cookie : cookies) {
sb.append(cookie.toString());
}
String cookie = sb.toString();
return cookie;
}
/**
* 添加任务,返回任务id
* @param jobInfo
* @return
*/
public int addXxlJob(XxlJobInfo jobInfo){
String path = url+ "/jobinfo/add";
if (StringUtils.isBlank(cookie)) {
cookie = getCookie();
}
jobInfo.setJobGroup(jobGroup);
jobInfo.setExecutorRouteStrategy("FIRST");
jobInfo.setGlueType(GlueTypeEnum.BEAN.name());
jobInfo.setExecutorBlockStrategy(ExecutorBlockStrategyEnum.SERIAL_EXECUTION.name());
jobInfo.setExecutorTimeout(0);
jobInfo.setExecutorFailRetryCount(0);
jobInfo.setGlueRemark("GLUE代码初始化");
jobInfo.setAuthor("创建任务人的名称");
jobInfo.setAlarmEmail("你的邮箱");
HttpResponse response = HttpRequest.post(path).form(JSON.parseObject(JSON.toJSONString(jobInfo),Map.class)).execute();
if (HttpStatus.HTTP_OK != response.getStatus()) {
// TODO
throw new LogicException("请求失败");
}
JSONObject jsonObject = JSON.parseObject(response.body());
if(HttpStatus.HTTP_OK != jsonObject.getIntValue("code")){
throw new LogicException("添加失败,"+jsonObject.getIntValue("msg"));
}
int jobId = jsonObject.getIntValue("content");
return jobId;
}
/**
* 删除任务
* @param id
*/
public boolean deleteXxlJob(int id){
String path = url+ "/jobinfo/remove";
Map<String, Object> paramMap = new HashMap<>();
paramMap.put("id", id);
if (StringUtils.isBlank(cookie)) {
cookie = getCookie();
}
HttpResponse response = HttpRequest.post(path).form(paramMap).execute();
if (HttpStatus.HTTP_OK != response.getStatus()) {
// TODO
throw new LogicException("请求失败");
}
JSONObject jsonObject = JSON.parseObject(response.body());
if(HttpStatus.HTTP_OK != jsonObject.getIntValue("code")){
throw new LogicException("删除失败,"+jsonObject.getIntValue("msg"));
}
return true;
}
/**
* 修改任务
* @param jobInfo
* @return
*/
public boolean updateXxlJob(XxlJobInfo jobInfo){
String path = url+ "/jobinfo/update";
if (StringUtils.isBlank(cookie)) {
cookie = getCookie();
}
HttpResponse response = HttpRequest.post(path).form(JSON.parseObject(JSON.toJSONString(jobInfo),Map.class)).execute();
if (HttpStatus.HTTP_OK != response.getStatus()) {
// TODO
throw new LogicException("请求失败");
}
JSONObject jsonObject = JSON.parseObject(response.body());
if(HttpStatus.HTTP_OK != jsonObject.getIntValue("code")){
throw new LogicException("修改失败,"+jsonObject.getIntValue("msg"));
}
return true;
}
/**
* 启动任务
* @param id
* @return
*/
public boolean stopXxlJob(int id){
String path = url+ "/jobinfo/start";
if (StringUtils.isBlank(cookie)) {
cookie = getCookie();
}
Map<String, Object> paramMap = new HashMap<>();
paramMap.put("id", id);
HttpResponse response = HttpRequest.post(path).form(paramMap).execute();
if (HttpStatus.HTTP_OK != response.getStatus()) {
// TODO
throw new LogicException("请求失败");
}
JSONObject jsonObject = JSON.parseObject(response.body());
if(HttpStatus.HTTP_OK != jsonObject.getIntValue("code")){
throw new LogicException("启动失败,"+jsonObject.getIntValue("msg"));
}
return true;
}
/**
* 停止任务
* @param id
* @return
*/
public boolean puseXxlJob(int id){
String path = url+ "/jobinfo/stop";
if (StringUtils.isBlank(cookie)) {
cookie = getCookie();
}
Map<String, Object> paramMap = new HashMap<>();
paramMap.put("id", id);
HttpResponse response = HttpRequest.post(path).form(paramMap).execute();
if (HttpStatus.HTTP_OK != response.getStatus()) {
// TODO
throw new LogicException("请求失败");
}
JSONObject jsonObject = JSON.parseObject(response.body());
if(HttpStatus.HTTP_OK != jsonObject.getIntValue("code")){
throw new LogicException("停止失败,"+jsonObject.getIntValue("msg"));
}
return true;
}
/**
* 根据id来查询数据
* @param id
* @return
*/
public XxlJobInfo getXxlJob(int id){
String path = url+ "/jobinfo/get";
Map<String, Object> paramMap = new HashMap<>();
paramMap.put("id", id);
if (StringUtils.isBlank(cookie)) {
cookie = getCookie();
}
HttpResponse response = HttpRequest.post(path).form(paramMap).execute();
if (HttpStatus.HTTP_OK != response.getStatus()) {
// TODO
throw new LogicException("请求失败");
}
JSONObject jsonObject = JSON.parseObject(response.body());
if(HttpStatus.HTTP_OK != jsonObject.getIntValue("code")){
throw new LogicException("查询失败,"+jsonObject.getIntValue("msg"));
}
ObjectMapper objectMapper = new ObjectMapper();
return objectMapper.convertValue(jsonObject.get("data"),XxlJobInfo.class);
}
1.新增:
public boolean inserCalendar() {
HttpClinet httpClinet = new HttpClinet();
//添加任务
XxlJobInfo xxlJobInfo = new XxlJobInfo();
//描述
xxlJobInfo.setJobDesc(“描述”);
//执行器,任务Handler名称
xxlJobInfo.setExecutorHandler("calendarTest");
xxlJobInfo.setJobCron(“cron表达式”);
//任务参数
xxlJobInfo.setExecutorParam(1);
//添加定时任务,返回定时任务id
int jobId = httpClinet.addXxlJob(xxlJobInfo);
return true;
}
1.修改:
public boolean updateCalendar() {
HttpClinet httpClinet = new HttpClinet();
//查询定时任务信息
XxlJobInfo xxlJobInfo = httpClinet.getXxlJob("定时任务id");
xxlJobInfo.setJobDesc(“描述”);
xxlJobInfo.setJobCron(“Cron表达式”);
httpClinet.updateXxlJob(xxlJobInfo);
return true;
}
#转换Cron表达式方法
/**
* 转换
* @param date
* @param dateFormat e.g:yyyy-MM-dd HH:mm:ss
* @return
*/
private static String formatDateByPattern(Date date, String dateFormat){
SimpleDateFormat sdf = new SimpleDateFormat(dateFormat);
String formatTimeStr = null;
if (date != null ) {
formatTimeStr = sdf.format(date);
}
return formatTimeStr;
}
#String转换Date方法
/**
* 转换 时间
* @param reminderTime 时间
* @param pattern 格式yyyy-MM-dd HH:mm:ss
* @return
*/
public static Date transFormaTionData(String reminderTime, String pattern) {
try{
SimpleDateFormat dateformat = new SimpleDateFormat(pattern);
return dateformat.parse(reminderTime);
}catch (ParseException e) {
e.printStackTrace();
}
throw new LogicException("转换时间出现问题");
}
#调用转换Cron表达式方法
/**
* 获取cron表达式
* @param dateTime 时间2020-11-11 14:50:21
* @return 21 50 14 11 11 ? 2020
*/
private String jobCrons(String dateTime){
String crons = formatDateByPattern("ss mm HH dd MM ? yyyy",transFormaTionData(dateTime,"yyyy-MM-dd HH:mm:ss"));
return crons;
}
/**
* 获取月
* @param dateTime
* @return
*/
public static int obtainMonth(String dateTime){
try{
SimpleDateFormat format = new SimpleDateFormat("yyyy-MM-dd");
Date tmpDate = format.parse(dateTime);
Calendar calendar = Calendar.getInstance();
calendar.setTime(tmpDate);
return (calendar.get(Calendar.MONTH) + 1);
}catch (ParseException e){
e.printStackTrace();
}
throw new LogicException("获取月份出现问题");
}
/**
* 获取周
*/
public static int obtainWeek(String dateTime){
try{
SimpleDateFormat format = new SimpleDateFormat("yyyy-MM-dd");
Date tmpDate = format.parse(dateTime);
Calendar cal = Calendar.getInstance();
cal.setTime(tmpDate);
return cal.get(Calendar.DAY_OF_WEEK);
}catch (ParseException e){
e.printStackTrace();
}
throw new LogicException("获取周出现问题");
}
/**
* 获取第几周
* @param dateTime 时间
* @return
*/
public static int obtainWhatWeek(String dateTime){
try{
SimpleDateFormat format = new SimpleDateFormat("yyyy-MM-dd");
Date tmpDate = format.parse(dateTime);
Calendar calendar = Calendar.getInstance();
calendar.setTime(tmpDate);
return calendar.get(Calendar.DAY_OF_WEEK_IN_MONTH);
}catch (ParseException e){
e.printStackTrace();
}
throw new LogicException("获取月份出现问题");
}
/**
* 转换周
* @param dayoFweek
* @return
*/
public static String transFormaTionWeek(int dayoFweek){
switch (dayoFweek){
case 1:
return "SUN";
case 2:
return "MON";
case 3:
return "TUE";
case 4:
return "WED";
case 5:
return "THU";
case 6:
return "FRI";
case 7:
return "SAT";
default:
break;
}
throw new LogicException("转换周出现了问题");
}
/**
* 重复时间段
* @param repeatTime 0-不重复,1-每天重复,2每周重复,3-每月重复,4-每年重复,5-工作日重复
* @param reminderTime 提前多少分钟提醒
* @param startDate 开始日期
* @return
*/
private String cron(Integer repeatTime, String reminderTime,String startDate){
switch(repeatTime){
case 1:
//每天
return formatDateByPattern("ss mm HH * * ?",transFormaTionData(reminderTime,"hh:mm"));
case 2:
//每周
return formatDateByPattern("ss mm HH ? * "+transFormaTionWeek(obtainWeek(startDate)),transFormaTionData(reminderTime,"hh:mm"));
case 3:
//每月
return formatDateByPattern("ss mm HH ? * "+obtainWeek(startDate)+"#"+obtainWhatWeek(startDate)+"",transFormaTionData(reminderTime,"hh:mm"));
case 4:
//每年
return formatDateByPattern("ss mm HH ? "+obtainMonth(startDate)+" "+transFormaTionWeek(obtainWeek(startDate))+"",transFormaTionData(reminderTime,"hh:mm"));
case 5:
//工作日
return formatDateByPattern("ss mm HH ? * MON-FRI",transFormaTionData(reminderTime,"hh:mm"));
default:
return null;
}
}