1、引入相关依赖

maven:<dependency><groupId>com.xuxueli</groupId><artifactId>xxl-job-core</artifactId><version>2.2.0</version></dependency><dependency><groupId>commons-httpclient</groupId><artifactId>commons-httpclient</artifactId><version>3.0.1</version></dependency>

2、配置参数

yml配置:
xxl:job:login:username: admin   # 登录xxl-job的账号密码password: 123456admin:addresses: http://127.0.0.1:8080/xxl-job-admin  # xxl-job服务地址accessToken:executor:appname: abcccc   # 执行器对应appnameaddress:ip:port: 9999  # 默认9999  可自定义logpath: /home/zwapp/apache-tomcat-8.5.61/gxjg/gx-hlwcjlogretentiondays: 30group: 7 # 执行器ID 

3、注入spring容器

package cn.com.thtf.hlwcj.config;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;/*** @author bo*/
@SuppressWarnings("ALL")
@Configuration
public class XxlJobConfig {private Logger logger = LoggerFactory.getLogger(XxlJobConfig.class);@Value("${xxl.job.admin.addresses}")private String adminAddresses;@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.accessToken}")private String accessToken;@Value("${xxl.job.executor.logpath}")private String logPath;@Value("${xxl.job.executor.logretentiondays}")private int logRetentionDays;@Beanpublic 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;}
}

4、调用xxl-job服务工具类  新版会有登录校验  见XxlJobUtil1

XxlJobUtil:

package cn.com.thtf.hlwcj.util;import cn.com.thtf.hlwcj.config.CustomConstants;
import cn.com.thtf.hlwcj.module.GxHlwcjScanFrequencyEntity;
import cn.com.thtf.hlwcj.module.XxlJobInfo;
import cn.com.thtf.hlwcj.vo.UpdateNetDataGatherTaskVO;
import com.alibaba.fastjson.JSONArray;
import com.alibaba.fastjson.JSONObject;
import com.google.common.base.Joiner;
import com.xxl.job.core.biz.model.ReturnT;
import com.xxl.job.core.util.DateUtil;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.httpclient.HttpClient;
import org.apache.commons.httpclient.HttpException;
import org.apache.commons.httpclient.HttpMethod;
import org.apache.commons.httpclient.methods.PostMethod;
import org.apache.commons.httpclient.methods.RequestEntity;
import org.apache.commons.httpclient.methods.StringRequestEntity;
import org.apache.commons.lang3.StringUtils;
import org.apache.http.entity.ContentType;
import org.yaml.snakeyaml.util.UriEncoder;import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.util.ArrayList;
import java.util.Date;
import java.util.List;/**** //todo 新增和更新都是表单提交** @author bo* @date 2021/4/19* @description*/
@Slf4j
public class XxlJobUtil {/*** 新增/编辑任务* @param url* @param param* @return* @throws HttpException* @throws IOException*/public static JSONObject addJob(String url, String param) throws Exception{PostMethod post = new PostMethod(url + "/jobinfo/add");JSONObject result = getXxlJobData(param, post);return result;}public static JSONObject updateJob(String url, String param) throws IOException {PostMethod post = new PostMethod(url + "/jobinfo/update");JSONObject result = getXxlJobData(param, post);return result;}/*** 删除任务* @param url* @param jobId* @return* @throws HttpException* @throws IOException*/public static JSONObject deleteJob(String url,int jobId) throws HttpException, IOException {String param = "id=" + jobId;PostMethod post = new PostMethod(url + "/jobinfo/remove");JSONObject result = getXxlJobData(param, post);return result;}/*** 开始任务** @param url* @param jobId* @return* @throws HttpException* @throws IOException*/public static JSONObject startJob(String url, int jobId) throws HttpException, IOException {String param = "id=" + jobId;PostMethod post = new PostMethod(url + "/jobinfo/start");JSONObject result = getXxlJobData(param, post);return result;}/*** 停止任务** @param url* @param jobId* @return* @throws HttpException* @throws IOException*/public static JSONObject stopJob(String url, int jobId) throws HttpException, IOException {String param = "id=" + jobId;PostMethod post = new PostMethod(url + "/jobinfo/stop");JSONObject result = getXxlJobData(param, post);return result;}/*** 手动执行任务** @param url* @param param* @return* @throws HttpException* @throws IOException*/public static JSONObject executeJob(String url, String param) throws HttpException, IOException {PostMethod post = new PostMethod(url + "/jobinfo/trigger");JSONObject result = getXxlJobData(param, post);return result;}/*** 获取任务列表** @param url* @param param* @return* @throws IOException*/public static JSONObject getTaskList(String url, String param) throws IOException {PostMethod post = new PostMethod(url + "/jobinfo/pageList");JSONObject result = getXxlJobData(param, post);return result;}/*** 获取任务下一次执行时间** @param url* @param param* @return* @throws IOException*/public static JSONObject getTaskNextTriggerTime(String url, String param) throws IOException {PostMethod post = new PostMethod(url + "/jobinfo/nextTriggerTime");JSONObject result = getXxlJobData(param, post);return result;}public static  String getTaskNextTime(String url, String cron) {try {if (StringUtils.isNotBlank(cron)) {String taskNestTimeParams = Joiner.on("&").join("scheduleType=CRON","scheduleConf=" + UriEncoder.encode(cron));JSONObject response = getTaskNextTriggerTime(url, taskNestTimeParams);if (response.containsKey(CustomConstants.REQUEST_CODE) && 200 == (Integer) response.get(CustomConstants.REQUEST_CODE)) {JSONArray content = response.getJSONArray("content");return content.getString(0);}}} catch (Exception e) {e.printStackTrace();}return StringUtils.EMPTY;}/*** 根据xxl-appname获取对应id** @param url* @param appnameParam* @return* @throws HttpException* @throws IOException*/public static JSONObject getAppNameIdByAppname(String url, String appnameParam) throws HttpException, IOException {String param = "appnameParam=" + appnameParam;PostMethod post = new PostMethod(url + "/jobgroup/getAppNameIdByAppname");JSONObject result = getXxlJobData(param, post);return result;}private static JSONObject getXxlJobData(String param, PostMethod post) throws IOException {HttpClient httpClient = new HttpClient();post.setRequestHeader("Content-Type", "application/x-www-form-urlencoded; charset=UTF-8");RequestEntity requestEntity = new StringRequestEntity(param, ContentType.APPLICATION_JSON.getMimeType(), "utf-8");post.setRequestEntity(requestEntity);httpClient.executeMethod(post);JSONObject result = new JSONObject();result = getJsonObject(post, result);return result;}private static JSONObject getJsonObject(HttpMethod get, JSONObject result) throws IOException {InputStream inputStream = get.getResponseBodyAsStream();BufferedReader br = new BufferedReader(new InputStreamReader(inputStream));StringBuffer stringBuffer = new StringBuffer();String str = "";while ((str = br.readLine()) != null) {stringBuffer.append(str);}if (get.getStatusCode() == 200) {/***  使用此方式会出现*  Going to buffer response body of large or unknown size. Using getResponseBodyAsStream instead is recommended.*  异常*  String responseBodyAsString = get.getResponseBodyAsString();*  result = JSONObject.parseObject(responseBodyAsString);*/result = JSONObject.parseObject(stringBuffer.toString());} else {try {
//                result = JSONObject.parseObject(get.getResponseBodyAsString());result = JSONObject.parseObject(stringBuffer.toString());} catch (Exception e) {result.put("error", stringBuffer.toString());}}return result;}}

XxlJobUtil1:


import cn.hutool.http.HttpRequest;
import cn.hutool.http.HttpResponse;
import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONObject;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.httpclient.Cookie;
import org.apache.commons.httpclient.HttpClient;
import org.apache.commons.httpclient.HttpException;
import org.apache.commons.httpclient.HttpMethod;
import org.apache.commons.httpclient.methods.GetMethod;
import org.apache.commons.httpclient.methods.PostMethod;import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStream;
import java.io.InputStreamReader;@Slf4j
public class XxlJobUtil1 {//自己本地测试的时候,直接把管理页的cookie放在这里就能用,偷个懒private static String cookie="xxljob_adminlte_settings=on; XXL_JOB_LOGIN_IDENTITY=7b226964223a312c22757365726e616d65223a2261646d696e222c2270617373776f7264223a226531306164633339343962613539616262653536653035376632306638383365222c22726f6c65223a312c227065726d697373696f6e223a6e756c6c7d";/*** 新增/编辑任务* @param url* @param requestInfo* @return* @throws HttpException* @throws IOException*/public static JSONObject addJob(String url, JSONObject requestInfo) throws HttpException, IOException {String path = "/jobinfo/add";String targetPath=url+path;cookie=getCookie();HttpResponse response = HttpRequest.post(targetPath).form(requestInfo).cookie(cookie).execute();JSONObject jsonObject = JSON.parseObject(response.body());return jsonObject;}public static JSONObject updateJob(String url, JSONObject requestInfo) throws HttpException, IOException {String path = "/jobinfo/update";String targetPath=url+path;cookie=getCookie();HttpResponse response = HttpRequest.post(targetPath).form(requestInfo).cookie(cookie).execute();JSONObject jsonObject = JSON.parseObject(response.body());return jsonObject;}/*** 删除任务* @param url* @param id* @return* @throws HttpException* @throws IOException*/public static JSONObject deleteJob(String url,int id) throws HttpException, IOException {String path = "/jobinfo/remove?id=" + id;String targetPath=url+path;cookie=getCookie();HttpResponse response = HttpRequest.post(targetPath).cookie(cookie).execute();JSONObject jsonObject = JSON.parseObject(response.body());return jsonObject;}/*** 开始任务* @param url* @param id* @return* @throws HttpException* @throws IOException*/public static JSONObject startJob(String url,int id) throws HttpException, IOException {String path = "/jobinfo/start?id="+id;String targetPath=url+path;cookie=getCookie();HttpResponse response = HttpRequest.post(targetPath).cookie(cookie).execute();JSONObject jsonObject = JSON.parseObject(response.body());return jsonObject;}/*** 停止任务* @param url* @param id* @return* @throws HttpException* @throws IOException*/public static JSONObject stopJob(String url,int id) throws HttpException, IOException {String path = "/jobinfo/stop?id="+id;String targetPath=url+path;cookie=getCookie();HttpResponse response = HttpRequest.post(targetPath).cookie(cookie).execute();JSONObject jsonObject = JSON.parseObject(response.body());return jsonObject;}/*** 根据xxl-appname获取对应id* @param url* @param appnameParam* @return* @throws HttpException* @throws IOException*/public static JSONObject getAppNameIdByAppname(String url,String appnameParam) throws HttpException, IOException {String path = "/jobgroup/getAppNameIdByAppname?appnameParam="+appnameParam;String targetPath=url+path;cookie=getCookie();HttpResponse response = HttpRequest.post(targetPath).cookie(cookie).execute();JSONObject jsonObject = JSON.parseObject(response.body());return jsonObject;}public static JSONObject doGet(String url,String path) throws HttpException, IOException {String targetUrl = url + path;HttpClient httpClient = new HttpClient();HttpMethod get = new GetMethod(targetUrl);get.setRequestHeader("cookie", cookie);httpClient.executeMethod(get);JSONObject result = new JSONObject();result = getJsonObject(get, result);return result;}private static JSONObject getJsonObject(HttpMethod get, JSONObject result) throws IOException {InputStream inputStream = get.getResponseBodyAsStream();BufferedReader br = new BufferedReader(new InputStreamReader(inputStream));StringBuffer stringBuffer = new StringBuffer();String str = "";while ((str = br.readLine()) != null) {stringBuffer.append(str);}if (get.getStatusCode() == 200) {/***  使用此方式会出现*  Going to buffer response body of large or unknown size. Using getResponseBodyAsStream instead is recommended.*  异常*  String responseBodyAsString = get.getResponseBodyAsString();*  result = JSONObject.parseObject(responseBodyAsString);*/result = JSONObject.parseObject(stringBuffer.toString());} else {try {
//                result = JSONObject.parseObject(get.getResponseBodyAsString());result = JSONObject.parseObject(stringBuffer.toString());} catch (Exception e) {result.put("error", stringBuffer.toString());}}return result;}public static String login(String url, String userName, String password) throws HttpException, IOException {String path = "/login?userName="+userName+"&password="+password;String targetUrl = url + path;HttpClient httpClient = new HttpClient();PostMethod get = new PostMethod(targetUrl);httpClient.executeMethod(get);if (get.getStatusCode() == 200) {Cookie[] cookies = httpClient.getState().getCookies();StringBuffer tmpcookies = new StringBuffer();for (Cookie c : cookies) {tmpcookies.append(c.toString() + ";");}cookie = tmpcookies.toString();} else {try {cookie = "";} catch (Exception e) {cookie="";}}return cookie;}/*** @Description 获取登录cookie* @Author  chengweiping* @Date   2021/4/13 16:39*/public static String getCookie() {return cookie;}public static void setCookie(String cookie) {XxlJobUtil1.cookie = cookie;}
}

5、执行器代码,直接处理你的业务就行了

import com.thtf.data.platform.worker.entity.XxlJobInfoEntity;
import com.thtf.data.platform.worker.mapper.XxlJobInfoMapper;
import com.thtf.data.platform.worker.service.IDataSynService;
import com.xxl.job.core.biz.model.ReturnT;
import com.xxl.job.core.handler.IJobHandler;
import com.xxl.job.core.handler.annotation.XxlJob;
import lombok.extern.slf4j.Slf4j;
import org.springframework.stereotype.Component;import javax.annotation.Resource;
import java.sql.Timestamp;
import java.util.Date;/*** 1、简单任务示例(Bean模式)* !!!依赖xxl-job-core版本>=2.3.0时** @author bo*/
@Component
@Slf4j
public class GxhlwcjJorHandler  extends IJobHandler {@XxlJob(value = "HlwcjJobHandler")public ReturnT<String> execute(String myId) throws Exception {System.out.println("-----------------------------");}
}旧版本
//@JobHandler(value = "demoJobHandler")
//@Component
//@Slf4j
//public class DemoJobHandler extends IJobHandler {
//
//    @Override
//    public ReturnT<String> execute(String s) throws Exception {
//        System.out.println("=====hello world=====");
//        return ReturnT.SUCCESS;
//    }}

Springboot整合xxl-job实现任务自定义定时任务相关推荐

  1. springboot整合redis、mybatis、@EnableScheduling定时任务,实现日访问量与日活量的统计与记录

    目录 一.实现目标 二.windows版本redis下载与安装 三.springboot集成redis 四.springboot集成mybatis 集成通用mapper 五.实现日访问量 @Enabl ...

  2. 2022-12-08 SSM项目转springboot整合jsp

    目录 1.添加springboot相关pom依赖 2.Springboot整合jsp 2.1.使用打jar包方式执行 2.2.打war包执行 3.多数据源xml文件配置提取 3.1.数据源bean提取 ...

  3. springBoot整合beetlsql

    springBoot整合BeetlSQL 文章摘要:本文主要介绍springBoot整合BeetlSQL,以及BeetlSQL自定义sql使用. 注:本例中,数据库将使用mysql,数据源使用阿里数据 ...

  4. springboot整合shiro和session的详细过程和自定义登录拦截器

    文章目录 1.shiro依赖 2.shiro配置 shiro过滤器配置: 关联自定义的其他管理器 自定义会话工厂: 3.登陆时记录用户信息 4.shiro一些工具类的学习 5.自定义登录拦截器 shi ...

  5. Spring Boot定时任务-SpringBoot整合Quartz

    如何通过SpringBoot整合Quartz框架,我们首先去创建一个项目,接下来我们需要在pom文件里添加坐标,我们在使用SpringBoot整合Quartz的时候,需要添加哪些坐标呢,我们来看一下, ...

  6. SpringBoot整合定时任务和邮件发送(邮箱 信息轰炸 整蛊)

    SpringBoot整合定时任务和邮件发送(邮箱 信息轰炸 整蛊) 目录 SpringBoot整合定时任务和邮件发送(邮箱 信息轰炸 整蛊) 1.概述 2.最佳实践 2.1创建项目引入依赖(mail) ...

  7. springboot整合springsecurity安全框架(后端spring_security模块代码可直接使用,根据需求自定义修改)

    SpringSecurity简介 最下面有与springboot整合的模块代码 用户认证和用户授权 主要包含两部分:用户认证和用户授权 用户认证:进入用户登录时候,输入用户名密码,查询数据库查看是否正 ...

  8. SpringBoot整合AlertManager,实现自定义的告警收敛以及邮件处理,告警风暴,解决重复告警问题

    SpringBoot整合AlertManager,实现自定义的告警收敛以及邮件处理,告警风暴,解决重复告警问题 需求 将传感器通过Http发送到微服务(SpringBoot项目)的警报消息,通知给对应 ...

  9. SpringBoot 整合JWT实现基于自定义注解的-登录请求验证拦截(保姆级教学,附:源码)

    学习目标: Spring Boot 整合JWT实现基于自定义注解的 登录请求接口拦截 例: 一篇掌握 JWT 入门知识  1.1 在学习SpringBoot 整合JWT之前,我们先来说说JWT进行用户 ...

  10. SpringBoot整合定时任务和Emil发送

    SpringBoot整合定时任务和Emil发送 定时任务 ​ 任务系统指的是定时任务.定时任务是企业级开发中必不可少的组成部分,诸如长周期业务数据的计算,例如年度报表,诸如系统脏数据的处理,再比如系统 ...

最新文章

  1. 路由器:访问控制列表
  2. mysql 5.7_MySQL 5.7新特性介绍
  3. 简单的正则表达式过滤网址
  4. CVPR 2021 | 澳洲国立大学提出基于模型的图像风格迁移
  5. 【leetcode】521. Longest Uncommon Subsequence I
  6. 委托BegionInvoke和窗体BegionInvoke
  7. Appium python adb命令
  8. 微信小程序需要的软件下载
  9. 用css制作旋转的立方体
  10. 数据中心网络架构 — 网络带宽的收敛比
  11. linux防病毒软件_十大Linux最佳防病毒软件-Linux防病毒软件列表!
  12. 短视频App开发方案IOS架构
  13. C#重点知识详解(转)
  14. kubernetes—ConfigMap 与 Secret
  15. 关于python接口基础到进阶随笔
  16. 8月8日科技快讯:库比蒂诺想修超级高铁,市长点名要苹果掏钱
  17. js判断 pc 手机 浏览器
  18. pythonista官网-Pythonista中文文档
  19. 计算机会计表格应用所有知识,电子表格
  20. 第1课:BPMN介绍

热门文章

  1. ABAP开发中常用的两个F4搜索帮助函数的区别
  2. SAP 取月度期初库存和月度期末库存(历史库存)
  3. SAP实施需注意问题总结
  4. AIX 下磁盘 I/O 性能分析
  5. 为什么美团打车、滴滴外卖必败?君智谢伟山揭秘了背后的竞争战略逻辑
  6. linux汇编和x86汇编,linux平台学x86汇编(四):从“hello world!”开始
  7. python上传excel文件_flask上传excel文件,无须存储,直接读取内容
  8. 如何解决java乱码_java如何解决乱码
  9. git linux 登陆_Git安装及基础命令
  10. oracle 数字不用,oracle – Plsql将数字(货币)拼写为意大利货币而不用硬编码的翻译编号...