调度任务xxl-job,定时器任务
作者:互联网
定时器任务的使用
1、配置信息
#xxl-job xxl: job: admin: addresses: http://12.0.0.1:8080/xxl-job-admin username: admin password: admin executor: address: # 执行器名称 appname: xxl-job-test-sync-job # 任务信息描述 jobdesc: 定时任务 ip: port: 9999 logpath: logretentiondays: 30 accessToken:
/** * xxl-job config * * @author guan */ @Configuration public class XxlJobConfig { private Logger logger = LoggerFactory.getLogger(XxlJobConfig.class); @Value("${xxl.job.admin.addresses}") private String adminAddresses; @Value("${xxl.job.admin.username}") private String username; @Value("${xxl.job.admin.password}") private String password; @Value("${xxl.job.accessToken}") private String accessToken; @Value("${xxl.job.executor.appname}") private String appname; @Value("${xxl.job.executor.jobdesc}") private String jobdesc; @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; public static final String JOB_INFO_UPDATE = "/jobinfo/update"; // 任务更新 public static final String JOB_INFO_LIST = "/jobinfo/pageList"; // 任务列表 public static final String JOB_GROUP_LIST = "/jobgroup/pageList"; // 任务组列表 public static final String JOB_LOGIN = "/login"; // 登录 @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; } }
2.调用xxl-job服务接口更新任务信息
/** * 获取cookie * * @return */ public String getCookie() { String path = adminAddresses + JOB_LOGIN; Map<String,Object> hashMap = new HashMap<>(); hashMap.put("userName", username); hashMap.put("password", password); HttpResponse response = HttpRequest.post(path).form(hashMap).execute(); List<HttpCookie> cookies = response.getCookies(); StringBuilder builder = new StringBuilder(); for (HttpCookie cookie : cookies) { builder.append(cookie.toString()); } return String.valueOf(builder); }
/** * 获取jogGroup的id * * @param jobgroupPath * @return * @throws Exception */ public int getJobGroupId(String jobgroupPath){ Map<String, Object> jobgroupParamMap = new HashMap<>(); //获取jobGroup的Id jobgroupParamMap.put("appname", appname); HttpResponse jobgroupResponse = HttpRequest.post(adminAddresses + jobgroupPath).form(jobgroupParamMap).execute(); // 拿到数据进行转换 Map<String, Object> stringObjectMap = JSON.parseObject(jobgroupResponse.body(), new TypeReference<Map<String, Object>>() {}); List<XxlJobGroup> xxlJobGroupList = JSON.parseArray(String.valueOf(stringObjectMap.get("data")),XxlJobGroup.class); return xxlJobGroupList.get(0).getId(); }
/** * 更新定时器 * @param duplicationStrategyVo * @return */ public int updateJob() { int jobId = 0; getCookie();//获取cookie // 获取任务详情 XxlJobInfo xxlJobInfo = getXxlJobInfo(jobdesc);try { String path = adminAddresses + JOB_INFO_UPDATE; Map<String, Object> paramMap = new HashMap<>(); paramMap.put("id", xxlJobInfo.getId()); paramMap.put("jobGroup", getJobGroupId(JOB_GROUP_LIST)); paramMap.put("jobDesc", xxlJobInfo.getJobDesc()); paramMap.put("executorRouteStrategy", xxlJobInfo.getExecutorRouteStrategy());// 路由策略 paramMap.put("glueType", xxlJobInfo.getGlueType()); paramMap.put("executorHandler", xxlJobInfo.getExecutorHandler()); // 此处hander需提前在项目中定义 paramMap.put("executorBlockStrategy", xxlJobInfo.getExecutorBlockStrategy()); paramMap.put("executorTimeout", xxlJobInfo.getExecutorTimeout()); paramMap.put("executorFailRetryCount", xxlJobInfo.getExecutorFailRetryCount());//执行失败重试 paramMap.put("author", xxlJobInfo.getAuthor()); paramMap.put("scheduleType", xxlJobInfo.getScheduleType()); paramMap.put("scheduleConf", xxlJobInfo.getScheduleConf()); paramMap.put("glueRemark", xxlJobInfo.getGlueRemark()); paramMap.put("triggerStatus", xxlJobInfo.getTriggerStatus()); //调度状态:0-停止,1-运行 paramMap.put("misfireStrategy", xxlJobInfo.getMisfireStrategy()); paramMap.put("executorParam", xxlJobInfo.getExecutorParam());//入参 HttpResponse response = HttpRequest.post(path).form(paramMap).execute(); if (HttpStatus.HTTP_OK != response.getStatus()) { logger.error("任务:{} 定时器更新失败", xxlJobInfo.getExecutorParam()); } JSONObject jsonObject = JSON.parseObject(response.body()); jobId = jsonObject.getIntValue("content"); } catch (Exception e) { logger.error("任务:{} 定时器创建失败", xxlJobInfo.getExecutorParam(), e); } return jobId; }
/** * Created by guan */ public class XxlJobGroup { private int id; private String appname; private String title; private int addressType; // 执行器地址类型:0=自动注册、1=手动录入 private String addressList; // 执行器地址列表,多地址逗号分隔(手动录入) private Date updateTime; // registry list private List<String> registryList; // 执行器地址列表(系统注册) public List<String> getRegistryList() { if (addressList!=null && addressList.trim().length()>0) { registryList = new ArrayList<>(Arrays.asList(addressList.split(","))); } return registryList; } public int getId() { return id; } public void setId(int id) { this.id = id; } public String getAppname() { return appname; } public void setAppname(String appname) { this.appname = appname; } public String getTitle() { return title; } public void setTitle(String title) { this.title = title; } public int getAddressType() { return addressType; } public void setAddressType(int addressType) { this.addressType = addressType; } public String getAddressList() { return addressList; } public Date getUpdateTime() { return updateTime; } public void setUpdateTime(Date updateTime) { this.updateTime = updateTime; } public void setAddressList(String addressList) { this.addressList = addressList; } }
/** * xxl-job info * * @author guan */ @Data public class XxlJobInfo { private int id; // 主键ID private int jobGroup; // 执行器主键ID private String jobDesc; private Date addTime; private Date updateTime; private String author; // 负责人 private String alarmEmail; // 报警邮件 private String scheduleType; // 调度类型 private String scheduleConf; // 调度配置,值含义取决于调度类型 private String misfireStrategy; // 调度过期策略 private String executorRouteStrategy; // 执行器路由策略 private String executorHandler; // 执行器,任务Handler名称 private String executorParam; // 执行器,任务参数 private String executorBlockStrategy; // 阻塞处理策略 private int executorTimeout; // 任务执行超时时间,单位秒 private int executorFailRetryCount; // 失败重试次数 private String glueType; // GLUE类型 #com.xxl.job.core.glue.GlueTypeEnum private String glueSource; // GLUE源代码 private String glueRemark; // GLUE备注 private Date glueUpdatetime; // GLUE更新时间 private String childJobId; // 子任务ID,多个逗号分隔 private int triggerStatus; // 调度状态:0-停止,1-运行 private long triggerLastTime; // 上次调度时间 private long triggerNextTime; // 下次调度时间 }
/** * 获取XxlJobInfo * * @param jobDesc * @return */ public XxlJobInfo getXxlJobInfo(String jobDesc){ String path = adminAddresses + JOB_INFO_LIST; Map<String, Object> paramMap = new HashMap<>(); paramMap.put("jobDesc", jobDesc); paramMap.put("jobGroup", getJobGroupId(JOB_GROUP_LIST)); paramMap.put("triggerStatus", -1); HttpResponse response = HttpRequest.post(path).form(paramMap).execute(); // 拿到数据进行转换 Map<String, Object> stringObjectMap = JSON.parseObject(response.body(), new TypeReference<Map<String, Object>>() {}); List<XxlJobInfo> list = JSON.parseArray(String.valueOf(stringObjectMap.get("data")),XxlJobInfo.class); return list.get(0); }
3.定时任务使用
/** * XxlJob开发示例(Bean模式) * * 开发步骤: * 1、任务开发:在Spring Bean实例中,开发Job方法; * 2、注解配置:为Job方法添加注解 "@XxlJob(value="自定义jobhandler名称", init = "JobHandler初始化方法", destroy = "JobHandler销毁方法")",注解value值对应的是调度中心新建任务的JobHandler属性的值。 * 3、执行日志:需要通过 "XxlJobHelper.log" 打印执行日志; * 4、任务结果:默认任务结果为 "成功" 状态,不需要主动设置;如有诉求,比如设置任务结果为失败,可以通过 "XxlJobHelper.handleFail/handleSuccess" 自主设置任务结果; * * @author guan */ @Slf4j @Component @Configuration public class SyncJob { /** * 调度任务 */ @XxlJob(value = "SynchronizationJob") public void execute(){
System.out.println("开始调度!");
}
}
标签:定时器,String,private,job,paramMap,put,public,xxl 来源: https://www.cnblogs.com/gakblog/p/16358622.html