1.在想要不要介紹呢榨了,哈哈哈哈
XXL-JOB就相當(dāng)于一個(gè)動(dòng)態(tài)的定時(shí)任務(wù)袍暴,可以動(dòng)態(tài)的去修改任務(wù)些侍,啟動(dòng)任務(wù)/停止任務(wù)隶症,以及終止任務(wù)。但是不能動(dòng)態(tài)的去創(chuàng)建定時(shí)任務(wù)岗宣,只能去調(diào)度中心去添加任務(wù)蚂会,嘿嘿不過我們可以通過 代碼直接訪問調(diào)度中心的接口然后創(chuàng)建定時(shí)任務(wù)。
2.下面我們正式開始
2.1 首先XXL-JOB的官網(wǎng)地址是: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 環(huán)境支持:
Maven3+
Jdk1.8+
Mysql5.7+
2.4 初始化“調(diào)度數(shù)據(jù)庫”
下載好XXL-JOB的源碼措嵌,解壓這個(gè)項(xiàng)目源碼,并獲取“調(diào)度數(shù)據(jù)庫初始化SQL腳本”芦缰,到mysql里面運(yùn)行sql腳本文件,“調(diào)度數(shù)據(jù)庫SQL腳本”位置是:/xxl-job/doc/db/tables_xxl_job.sql
2.5 項(xiàng)目源碼結(jié)構(gòu):
xxl-job-admin:調(diào)度中心
xxl-job-core:公共依賴
xxl-job-executor-samples:執(zhí)行器Sample示例(選擇合適的版本執(zhí)行器枫慷,可直接使用让蕾,也可以參考其并將現(xiàn)有項(xiàng)目改造成執(zhí)行器)
:xxl-job-executor-sample-springboot:Springboot版本,通過Springboot管理執(zhí)行器或听,推薦這種方式探孝;
:xxl-job-executor-sample-spring:Spring版本,通過Spring容器管理執(zhí)行器誉裆,比較通用顿颅;
:xxl-job-executor-sample-frameless:無框架版本;
:xxl-job-executor-sample-jfinal:JFinal版本足丢,通過JFinal管理執(zhí)行器粱腻;
:xxl-job-executor-sample-nutz:Nutz版本,通過Nutz管理執(zhí)行器斩跌;
:xxl-job-executor-sample-jboot:jboot版本绍些,通過jboot管理執(zhí)行器;
2.6 配置部署“調(diào)度中心”:
1.調(diào)度中心配置文件地址:/xxl-job/xxl-job admin/src/main/resources/application.properties耀鸦。
2調(diào)度中心配置內(nèi)容說明:
調(diào)度中心JDBC鏈接:鏈接地址請(qǐng)保持和 2.1章節(jié) 所創(chuàng)建的調(diào)度數(shù)據(jù)庫的地址一致
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報(bào)警郵箱
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調(diào)度中心通訊TOKEN [選填]:非空時(shí)啟用柬批;
xxl.job.accessToken=
調(diào)度中心國際化配置 [必填]: 默認(rèn)為 "zh_CN"/中文簡體, 可選范圍為 "zh_CN"/中文簡體, >"zh_TC"/中文繁體 and "en"/英文;
xxl.job.i18n=zh_CN
調(diào)度線程池最大線程配置【必填】
xxl.job.triggerpool.fast.max=200
xxl.job.triggerpool.slow.max=100調(diào)度中心日志表數(shù)據(jù)保存天數(shù) [必填]:過期日志自動(dòng)清理袖订;限制大于等于7時(shí)生效氮帐,否則, 如-1,關(guān)閉自動(dòng)清理功能洛姑;xxl.job.logretentiondays=30
按照上面的來配置完成以后上沐,將項(xiàng)目編譯打包。
window如何打包并運(yùn)行的:
SpringBoot打包成jar:image.png
項(xiàng)目目錄多了個(gè)target文件夾吏口,里面有剛才打包的jar文件奄容,運(yùn)行cmd冰更,到target這個(gè)文件夾里面,直接:java -jar 打包的文件名字.jar昂勒,就可以直接運(yùn)行了蜀细,如果不會(huì)用cmd到target這個(gè)文件夾里面,直接在打開這個(gè)target這個(gè)文件夾然后在輸入cmd就可以了戈盈。網(wǎng)址:輸入:http://localhost:8080/xxl-job-admin/jobinfo,就可以進(jìn)去了奠衔。image.png
image.png
2.7 項(xiàng)目使用XXL-JOB步驟:
1.下面開始使用自己的項(xiàng)目然后調(diào)用XXL-JOB里面的調(diào)度中心,maven依賴,在pom.xml文件中引用xxl-job-core塘娶,示例圖:image.png<dependency> <groupId>com.xuxueli</groupId> <artifactId>xxl-job-core</artifactId> <version>2.2.0</version> </dependency>
這里使用的是2.2.0版本归斤。
2.配置文件
2.1.寫配置文件的數(shù)據(jù),在application.yml里面刁岸,如:
xxl:
job:
admin:
addresses: http://localhost:8080/xxl-job-admin/jobinfo #任務(wù)管理器地址
userName: admin #賬戶
password: 123456 #密碼
ifRemember: on #
executor:
appname: xxl-job-executor-sample #執(zhí)行器的AppName名字
ip: ""#默認(rèn)為空
port: 9999
logpath: data/applogs/xxl-job/jobhandler
accessToken: 1111 #驗(yàn)證脏里,在調(diào)度中心中設(shè)置了,所以這邊也要設(shè)置虹曙,必須一樣
logretentiondays: 30
address:
#注意:配置執(zhí)行器的名稱迫横、IP地址、端口號(hào)酝碳,后面如果配置多個(gè)執(zhí)行器時(shí)矾踱,要防止端口沖突
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;
}
}
/**
* 針對(duì)多網(wǎng)卡、容器內(nèi)部署等情況疏哗,可借助 "spring-cloud-commons" 提供的 "InetUtils" 組件靈活定制注冊(cè)IP呛讲;
*
* 1、引入依賴:
* <dependency>
* <groupId>org.springframework.cloud</groupId>
* <artifactId>spring-cloud-commons</artifactId>
* <version>${version}</version>
* </dependency>
*
* 2返奉、配置文件贝搁,或者容器啟動(dòng)變量
* spring.cloud.inetutils.preferred-networks: 'xxx.xxx.xxx.'
*
* 3、獲取IP
* String ip_ = inetUtils.findFirstNonLoopbackHostInfo().getIpAddress();
*/
- 在項(xiàng)目中創(chuàng)建任務(wù)
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這個(gè)名字是你在添加定時(shí)任務(wù)的時(shí)候所需要的芽偏,他相當(dāng)于指定這個(gè)定時(shí)任務(wù)執(zhí)行的是哪一個(gè)
@XxlJob("calendarTest")
public ReturnT<String> calendarTest(String param) throws Exception {
//輸出你所傳的值
System.out.println(param);
return ReturnT.SUCCESS;
}
}
在調(diào)度中心中添加執(zhí)行器
image.png//注意:那個(gè)機(jī)器地址:是指的是你的ip地址驾胆,加上你在你項(xiàng)目里面添加的端口號(hào)放坏,因?yàn)槟銌?dòng)項(xiàng)目的時(shí)候他會(huì)在你項(xiàng)目里面在啟動(dòng)一個(gè)端口玫荣,那個(gè)端口璧针,就是你所需要的端口。
5.在調(diào)度中心中添加定時(shí)任務(wù)然后點(diǎn)擊操作十厢,選擇啟動(dòng)image.png就可以看到了等太,對(duì)了,你必須要先把你的那個(gè)項(xiàng)目啟動(dòng)蛮放,然后在點(diǎn)擊啟動(dòng)缩抡。然后去調(diào)度日志里面可以查看到是否啟動(dòng)成功了。image.png
6.動(dòng)態(tài)添加定時(shí)任務(wù):
我們可以通過httpClinet 直接調(diào)用任務(wù)新增接口包颁,動(dòng)態(tài)添加任務(wù)瞻想,但是有一個(gè)前提压真,xxl-job-admin增加了登錄鑒權(quán),任務(wù)的CRUD接口需要登錄信息蘑险,所以我們要先登錄才能調(diào)用接口滴肿。登錄代碼示例如下:
private String cookie;
//你部署的調(diào)度中心接口地址
private String url = "http://localhost:8080/xxl-job-admin/jobinfo";
//賬戶
private String userName = "admin";
//密碼
private String password = "123456";
//
private String ifRemember = "on";
//執(zhí)行器的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;
}
/**
* 添加任務(wù),返回任務(wù)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("創(chuàng)建任務(wù)人的名稱");
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("請(qǐng)求失敗");
}
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;
}
/**
* 刪除任務(wù)
* @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("請(qǐng)求失敗");
}
JSONObject jsonObject = JSON.parseObject(response.body());
if(HttpStatus.HTTP_OK != jsonObject.getIntValue("code")){
throw new LogicException("刪除失敗泼差,"+jsonObject.getIntValue("msg"));
}
return true;
}
/**
* 修改任務(wù)
* @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("請(qǐng)求失敗");
}
JSONObject jsonObject = JSON.parseObject(response.body());
if(HttpStatus.HTTP_OK != jsonObject.getIntValue("code")){
throw new LogicException("修改失敗,"+jsonObject.getIntValue("msg"));
}
return true;
}
/**
* 啟動(dòng)任務(wù)
* @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("請(qǐng)求失敗");
}
JSONObject jsonObject = JSON.parseObject(response.body());
if(HttpStatus.HTTP_OK != jsonObject.getIntValue("code")){
throw new LogicException("啟動(dòng)失敗呵俏,"+jsonObject.getIntValue("msg"));
}
return true;
}
/**
* 停止任務(wù)
* @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("請(qǐng)求失敗");
}
JSONObject jsonObject = JSON.parseObject(response.body());
if(HttpStatus.HTTP_OK != jsonObject.getIntValue("code")){
throw new LogicException("停止失敗堆缘,"+jsonObject.getIntValue("msg"));
}
return true;
}
/**
* 根據(jù)id來查詢數(shù)據(jù)
* @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("請(qǐng)求失敗");
}
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);
}
下面在方法中調(diào)用這些接口吧:
1.新增:
public boolean inserCalendar() {
HttpClinet httpClinet = new HttpClinet();
//添加任務(wù)
XxlJobInfo xxlJobInfo = new XxlJobInfo();
//描述
xxlJobInfo.setJobDesc(“描述”);
//執(zhí)行器普碎,任務(wù)Handler名稱
xxlJobInfo.setExecutorHandler("calendarTest");
xxlJobInfo.setJobCron(“cron表達(dá)式”);
//任務(wù)參數(shù)
xxlJobInfo.setExecutorParam(1);
//添加定時(shí)任務(wù)吼肥,返回定時(shí)任務(wù)id
int jobId = httpClinet.addXxlJob(xxlJobInfo);
return true;
}
1.修改:
public boolean updateCalendar() {
HttpClinet httpClinet = new HttpClinet();
//查詢定時(shí)任務(wù)信息
XxlJobInfo xxlJobInfo = httpClinet.getXxlJob("定時(shí)任務(wù)id");
xxlJobInfo.setJobDesc(“描述”);
xxlJobInfo.setJobCron(“Cron表達(dá)式”);
httpClinet.updateXxlJob(xxlJobInfo);
return true;
}
#轉(zhuǎn)換Cron表達(dá)式方法
/**
* 轉(zhuǎn)換
* @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轉(zhuǎn)換Date方法
/**
* 轉(zhuǎn)換 時(shí)間
* @param reminderTime 時(shí)間
* @param pattern 格式y(tǒng)yyy-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("轉(zhuǎn)換時(shí)間出現(xiàn)問題");
}
#調(diào)用轉(zhuǎn)換Cron表達(dá)式方法
/**
* 獲取cron表達(dá)式
* @param dateTime 時(shí)間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("獲取月份出現(xiàn)問題");
}
/**
* 獲取周
*/
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("獲取周出現(xiàn)問題");
}
/**
* 獲取第幾周
* @param dateTime 時(shí)間
* @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("獲取月份出現(xiàn)問題");
}
/**
* 轉(zhuǎn)換周
* @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("轉(zhuǎn)換周出現(xiàn)了問題");
}
/**
* 重復(fù)時(shí)間段
* @param repeatTime 0-不重復(fù),1-每天重復(fù)麻车,2每周重復(fù)潜沦,3-每月重復(fù),4-每年重復(fù)绪氛,5-工作日重復(fù)
* @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;
}
}