1.在想要不要介绍呢,哈哈哈哈
XXL-JOB就相当于一个动态的定时任务,可以动态的去修改任务,启动任务/停止任务,以及终止任务。但是不能动态的去创建定时任务,只能去调度中心去添加任务,嘿嘿不过我们可以通过 代码直接访问调度中心的接口然后创建定时任务。
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 项目源码结构:
xxl-job-admin:调度中心
xxl-job-core:公共依赖
xxl-job-executor-samples:执行器Sample示例(选择合适的版本执行器,可直接使用,也可以参考其并将现有项目改造成执行器)
:xxl-job-executor-sample-springboot:Springboot版本,通过Springboot管理执行器,推荐这种方式;
:xxl-job-executor-sample-spring:Spring版本,通过Spring容器管理执行器,比较通用;
:xxl-job-executor-sample-frameless:无框架版本;
:xxl-job-executor-sample-jfinal:JFinal版本,通过JFinal管理执行器;
:xxl-job-executor-sample-nutz:Nutz版本,通过Nutz管理执行器;
:xxl-job-executor-sample-jboot:jboot版本,通过jboot管理执行器;
2.6 配置部署“调度中心”:
1.调度中心配置文件地址:/xxl-job/xxl-job admin/src/main/resources/application.properties。
2调度中心配置内容说明:
调度中心JDBC链接:链接地址请保持和 2.1章节 所创建的调度数据库的地址一致
spring.datasource.url=jdbc:mysql://127.0.0.1:3306/xxl_job?Unicode=true&characterEncoding=UTF-8
spring.datasource.username=root
spring.datasource.password=root_pwd
spring.datasource.driver-class-name=com.mysql.jdbc.Driver报警邮箱
spring.mail.host=smtp.qq.com
spring.mail.port=25
spring.mail.username=xxx@qq.com
spring.mail.password=xxx
spring.mail.properties.mail.smtp.auth=true
spring.mail.properties.mail.smtp.starttls.enable=true
spring.mail.properties.mail.smtp.starttls.required=true
spring.mail.properties.mail.smtp.socketFactory.class=javax.net.ssl.SSLSocketFactory调度中心通讯TOKEN [选填]:非空时启用;
xxl.job.accessToken=
调度中心国际化配置 [必填]: 默认为 "zh_CN"/中文简体, 可选范围为 "zh_CN"/中文简体, >"zh_TC"/中文繁体 and "en"/英文;
xxl.job.i18n=zh_CN
调度线程池最大线程配置【必填】
xxl.job.triggerpool.fast.max=200
xxl.job.triggerpool.slow.max=100调度中心日志表数据保存天数 [必填]:过期日志自动清理;限制大于等于7时生效,否则, 如-1,关闭自动清理功能;xxl.job.logretentiondays=30
按照上面的来配置完成以后,将项目编译打包。
window如何打包并运行的:
SpringBoot打包成jar:
项目目录多了个target文件夹,里面有刚才打包的jar文件,运行cmd,到target这个文件夹里面,直接:java -jar 打包的文件名字.jar,就可以直接运行了,如果不会用cmd到target这个文件夹里面,直接在打开这个target这个文件夹然后在输入cmd就可以了。网址:输入:http://localhost:8080/xxl-job-admin/jobinfo,就可以进去了。
2.7 项目使用XXL-JOB步骤:
1.下面开始使用自己的项目然后调用XXL-JOB里面的调度中心,maven依赖,在pom.xml文件中引用xxl-job-core,示例图:<dependency> <groupId>com.xuxueli</groupId> <artifactId>xxl-job-core</artifactId> <version>2.2.0</version> </dependency>
这里使用的是2.2.0版本。
2.配置文件
2.1.写配置文件的数据,在application.yml里面,如:
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地址、端口号,后面如果配置多个执行器时,要防止端口冲突
2.2 添加配置文件XxlJobConfig.java
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;
}
}
在调度中心中添加执行器
//注意:那个机器地址:是指的是你的ip地址,加上你在你项目里面添加的端口号,因为你启动项目的时候他会在你项目里面在启动一个端口,那个端口,就是你所需要的端口。
5.在调度中心中添加定时任务然后点击操作,选择启动就可以看到了,对了,你必须要先把你的那个项目启动,然后在点击启动。然后去调度日志里面可以查看到是否启动成功了。
6.动态添加定时任务:
我们可以通过httpClinet 直接调用任务新增接口,动态添加任务,但是有一个前提,xxl-job-admin增加了登录鉴权,任务的CRUD接口需要登录信息,所以我们要先登录才能调用接口。登录代码示例如下:
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;
}
}