Java實(shí)現(xiàn)定時(shí)任務(wù)的示例代碼
xxl-job官網(wǎng)
https://www.xuxueli.com/xxl-job/
調(diào)用xxl-job中的xxl-job-admin模塊啟用
引入依賴
<!-- 調(diào)度任務(wù) -->
<dependency>
<groupId>com.xuxueli</groupId>
<artifactId>xxl-job-core</artifactId>
<version>2.3.0</version>
</dependency>配置信息(application.properties)
### 調(diào)度中心部署根地址 [選填]:如調(diào)度中心集群部署存在多個(gè)地址則用逗號分隔。執(zhí)行器將會使用該地址進(jìn)行"執(zhí)行器心跳注冊"和"任務(wù)結(jié)果回調(diào)";為空則關(guān)閉自動注冊; xxl.job.admin.addresses=http://127.0.0.1:8883/xxl-job-admin ### 執(zhí)行器通訊TOKEN [選填]:非空時(shí)啟用; xxl.job.accessToken=default_token ### 執(zhí)行器AppName [選填]:執(zhí)行器心跳注冊分組依據(jù);為空則關(guān)閉自動注冊 xxl.job.executor.appname=xxl-job-executor-sample ### 執(zhí)行器注冊 [選填]:優(yōu)先使用該配置作為注冊地址,為空時(shí)使用內(nèi)嵌服務(wù) ”IP:PORT“ 作為注冊地址。從而更靈活的支持容器類型執(zhí)行器動態(tài)IP和動態(tài)映射端口問題。 xxl.job.executor.address= ### 執(zhí)行器IP [選填]:默認(rèn)為空表示自動獲取IP,多網(wǎng)卡時(shí)可手動設(shè)置指定IP,該IP不會綁定Host僅作為通訊實(shí)用;地址信息用于 "執(zhí)行器注冊" 和 "調(diào)度中心請求并觸發(fā)任務(wù)"; xxl.job.executor.ip= ### 執(zhí)行器端口號 [選填]:小于等于0則自動獲??;默認(rèn)端口為9999,單機(jī)部署多個(gè)執(zhí)行器時(shí),注意要配置不同執(zhí)行器端口; xxl.job.executor.port=9999 ### 執(zhí)行器運(yùn)行日志文件存儲磁盤路徑 [選填] :需要對該路徑擁有讀寫權(quán)限;為空則使用默認(rèn)路徑; xxl.job.executor.logpath=/Users/linyanxia/Downloads/common/log/jobhandler ### 執(zhí)行器日志文件保存天數(shù) [選填] : 過期日志自動清理, 限制值大于等于3時(shí)生效; 否則, 如-1, 關(guān)閉自動清理功能; xxl.job.executor.logretentiondays=-1
配置類(XxlJobConfiguration)
@Slf4j
@Configuration
public class XxlJobConfiguration {
@Value("${xxl.job.admin.addresses}")
private String adminAddresses;
@Value("${xxl.job.executor.appname}")
private String appname;
@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;
@Bean
public XxlJobSpringExecutor xxlJobExecutor() {
log.info(">>>>>>>>>>> xxl-job config init.");
XxlJobSpringExecutor xxlJobSpringExecutor = new XxlJobSpringExecutor();
xxlJobSpringExecutor.setAdminAddresses(adminAddresses);
xxlJobSpringExecutor.setAppname(appname);
xxlJobSpringExecutor.setIp(ip);
xxlJobSpringExecutor.setPort(port);
xxlJobSpringExecutor.setAccessToken(accessToken);
xxlJobSpringExecutor.setLogPath(logPath);
xxlJobSpringExecutor.setLogRetentionDays(logRetentionDays);
return xxlJobSpringExecutor;
}
}調(diào)用xxl-job-admin模塊的接口
@Component
@Slf4j
public class XxlJobUtil {
// public static Logger logger = LoggerFactory.getLogger(ApiUtil.class);
private static String cookie="";
private static String prePath = "/jobinfo";
private static String xxlJobAdminHost;
public static JSONObject getPageList(Integer jobId,Integer pageSize,Integer pageNum) throws Exception {
//jobGroup: 2
//triggerStatus: -1
//jobDesc:
//executorHandler:
//author:
//start: 0
//length: 10
String path = prePath + "/pageList";
Map<String,Object> formMap = new HashMap<>();
formMap.put("jobGroup",1);
formMap.put("triggerStatus",-1);
formMap.put("start",(pageNum-1)*pageSize);
formMap.put("start",(pageNum-1)*pageSize);
formMap.put("length",pageSize);
formMap.put("jobId",jobId);
return doPost(xxlJobAdminHost,path,formMap);
}
// /findById
public static JSONObject getJobById(Integer jobId) throws Exception {
//jobGroup: 2
//triggerStatus: -1
//jobDesc:
//executorHandler:
//author:
//start: 0
//length: 10
String path = prePath + "/findById";
Map<String,Object> formMap = new HashMap<>();
formMap.put("jobId",jobId);
return doPost(xxlJobAdminHost,path,formMap);
}
/**
* 新增/編輯任務(wù)
* @param url
* @param requestInfo
*/
public static JSONObject addJob(String url,Map requestInfo) throws Exception {
String path = "/jobinfo/add";
return doPost(url,path,requestInfo);
}
/**
* 編輯任務(wù)
* /xxl-job-admin/jobinfo/update
*/
public static JSONObject editJobSchedule(Integer jobId,String schedule) throws Exception {
JSONObject jsonObject = XxlJobUtil.getJobById(jobId);
if (!jsonObject.getString("code").equals("200")){
throw new RuntimeException("沒有該調(diào)度任務(wù)");
}
Map<String,Object> formMap = new HashMap<>();
// formMap.put("id",jobId);
Iterator iter = jsonObject.getJSONObject("content").entrySet().iterator();
while (iter.hasNext()) {
Map.Entry entry = (Map.Entry) iter.next();
// System.out.println(entry.getKey().toString());
// System.out.println(entry.getValue().toString());
if (entry.getKey().toString().contains("scheduleConf")){
formMap.put(entry.getKey().toString(),schedule);
}else {
if (entry.getKey().toString().contains("Time")||entry.getKey().toString().contains("time")){
continue;
}
formMap.put(entry.getKey().toString(),entry.getValue());
}
}
formMap.put("cronGen_display",schedule);
formMap.put("schedule_conf_CRON",schedule);
// System.out.println(jsonObject);
//jobGroup: 1
//jobDesc: TB_SCYX_GCZB_TOP10_FACT
//author: admin
//alarmEmail:
//scheduleType: CRON
//scheduleConf: 1 17 11 ? * 3
//= //cronGen_display: 1 17 11 ? * 3
//= // schedule_conf_CRON: 1 17 11 ? * 3
//= //schedule_conf_FIX_RATE:
//= //schedule_conf_FIX_DELAY:
//executorHandler: testjob
//executorParam: TB_SCYX_GCZB_TOP10_FACT
//executorRouteStrategy: ROUND
//childJobId:
//misfireStrategy: DO_NOTHING
//executorBlockStrategy: SERIAL_EXECUTION
//executorTimeout: 0
//executorFailRetryCount: 0
//id: 26
String path = "/jobinfo/update";
JSONObject resultJson = doPost(xxlJobAdminHost,path,formMap);
if (!resultJson.getString("code").equals("200")){
throw new Exception("更新任務(wù)調(diào)度時(shí)間失敗");
}
return resultJson;
}
/**
* 刪除任務(wù)
* @param id
* @return
*/
public static JSONObject deleteJob(int id) throws Exception {
String path = "/jobinfo/remove";
Map<String,Object> formMap = new HashMap<>();
formMap.put("id",id);
return doPost(xxlJobAdminHost,path,formMap);
}
/**
* 單次執(zhí)行任務(wù)
* @param url
* @param id
* @param executorParam
* @return
*/
public static JSONObject triggerJob(String url,Integer id,String executorParam) throws Exception {
String path = "/jobinfo/trigger";
Map<String,Object> formMap = new HashMap<>();
formMap.put("id",id);
formMap.put("executorParam",executorParam);
return doPost(url,path,formMap);
}
/**
* 開始任務(wù)
* @param url
* @param id
* @return
*/
public static JSONObject startJob(String url,Integer id) throws Exception {
String path = "/jobinfo/start";
Map<String,Object> formMap = new HashMap<>();
formMap.put("id",id);
return doPost(url,path,formMap);
}
/**
* 停止任務(wù)
* @param url
* @param id
* @return
*/
public static JSONObject stopJob(String url, Integer id) throws Exception {
String path = "/jobinfo/stop";
Map<String,Object> formMap = new HashMap<>();
formMap.put("id",id);
return doPost(url,path,formMap);
}
public static JSONObject getLogPage(Integer jobId,String filterTime,Integer pageNum,Integer pageSize) throws Exception {
String path = "/joblog/pageList";
//jobGroup: 1
//jobId: 0
//logStatus: -1
//filterTime: 2021-09-01 00:00:00 - 2021-09-30 23:59:59
//start: 0
//length: 10
Map<String,Object> formMap = new HashMap<>();
formMap.put("jobId",jobId);
formMap.put("jobGroup",1);
formMap.put("logStatus",-1);
formMap.put("start",pageNum);
formMap.put("length",pageSize);
formMap.put("filterTime",filterTime);
return doPost(xxlJobAdminHost,path,formMap);
}
public static JSONObject getLogDetailCat(Integer logId,String executorAddress,Long triggerTime,Integer fromLineNum) throws Exception {
String path = "/joblog/logDetailCat";
//executorAddress: http://192.168.14.207:9946/
//triggerTime: 1633679504000
//logId: 1157
//fromLineNum: 159
Map<String,Object> formMap = new HashMap<>();
formMap.put("executorAddress",executorAddress);
formMap.put("triggerTime",triggerTime);
formMap.put("logId",logId);
formMap.put("fromLineNum",fromLineNum);
return doPost(xxlJobAdminHost,path,formMap);
}
public static JSONObject doPost(String url,String path,Map<String,Object> formMap) throws Exception {
String targetUrl = url + path;
HttpResponse response = HttpRequest.post(targetUrl)
.header("cookie", getCookie())
.form(formMap)
.execute();
JSONObject result = JSONObject.parseObject(response.body());
// && result.getString("code").equals("200")
if (response.getStatus() == 200){
return JSONObject.parseObject(response.body());
}else {
log.info("請求失敗,path:{}\n "+response.body(),path);
throw new RuntimeException("請求失敗\n "+response.body());
}
}
public static JSONObject doGet(String url,String path) {
String targetUrl = url + path;
JSONObject result = JSONObject.parseObject(HttpRequest.get(targetUrl)
.header("cookie", getCookie()).execute().body());
return result;
}
public static String login(String url, String userName, String password) {
String path = "/login";
String targetUrl = url + path;
Map<String,Object> loginMap = new HashMap<>();
loginMap.put("userName",userName);
loginMap.put("password",password);
HttpResponse response = HttpRequest.post(targetUrl)
.form(loginMap).execute();
if (response.getStatus() == 200) {
List<HttpCookie> cookies = response.getCookies();
StringBuffer tmpcookies = new StringBuffer();
for (HttpCookie c : cookies) {
tmpcookies.append(c.toString() + ";");
}
cookie = tmpcookies.toString();
} else {
cookie = "";
}
return cookie;
}
public static String getCookie(){
// System.out.println("getcookie:"+xxlJobAdminHost);
if (StringUtils.isNotBlank(cookie)){
return cookie;
}else {
return login(xxlJobAdminHost,"admin","123456");
}
}
@Value("${xxl.job.admin.addresses}")
public void setXxlJobAdminHost(String xxlJobAdminHost) {
XxlJobUtil.xxlJobAdminHost = xxlJobAdminHost;
}
}添加調(diào)度任務(wù)
Map<String,Object> requestInfo = new HashMap<>();
requestInfo.put("jobGroup",1);
requestInfo.put("jobDesc",collectorTask.getTaskName());
requestInfo.put("executorRouteStrategy","ROUND");
requestInfo.put("scheduleType","CRON");
requestInfo.put("cronGen_display",collectorTask.getDispatchTime());
requestInfo.put("scheduleConf",collectorTask.getDispatchTime());
requestInfo.put("schedule_conf_CRON",collectorTask.getDispatchTime());
requestInfo.put("glueType","BEAN");
requestInfo.put("executorHandler","startTasks");
requestInfo.put("executorBlockStrategy","SERIAL_EXECUTION");
requestInfo.put("misfireStrategy","DO_NOTHING");
requestInfo.put("executorTimeout",0);
requestInfo.put("executorFailRetryCount",0);
requestInfo.put("author","admin");
requestInfo.put("alarmEmail","");
requestInfo.put("executorParam",id);
requestInfo.put("glueRemark","GLUE代碼初始化");
com.alibaba.fastjson.JSONObject response= XxlJobUtil.addJob(addresses,requestInfo);
log.info("新增xxlJob任務(wù) {}",response);
if (!response.getString("code").equals("200")){
throw new Exception("新增任務(wù)調(diào)度失敗");
}
// 獲取生成調(diào)度任務(wù)ID。根據(jù)此ID去執(zhí)行調(diào)度任務(wù)
collectorTask.setXxlJobId(response.getInteger("content"));
// 刪除調(diào)度任務(wù)
XxlJobUtil.deleteJob(task_id.getXxlJobId());
// 修改調(diào)度任務(wù)
XxlJobUtil.editJobSchedule(collectorTask.getXxlJobId(),collectorTask.getDispatchTime());調(diào)度任務(wù)
@RestController
@RequestMapping("/apiSyncTask")
public class ApiSyncTaskController {
@Value("${xxl.job.admin.addresses}")
private String xxlJobAdminHost;
@Autowired(required = false)
private CollectorTaskMapper collectorTaskMapper;
// 單次啟動任務(wù)
@GetMapping("/trigger")
public R triggerTask(Integer id, String executorParam) {
try {
System.out.println(xxlJobAdminHost);
return R.ok(XxlJobUtil.triggerJob(xxlJobAdminHost, id, executorParam));
} catch (Exception e) {
e.printStackTrace();
return R.failed(e.getMessage());
}
}
// 啟動任務(wù)
@GetMapping("/start")
public R startTask(Integer id) {
try {
JSONObject jsonObject = XxlJobUtil.startJob(xxlJobAdminHost, id);
if (jsonObject.getString("code").equals("200")) {
CollectorTask task = new CollectorTask();
task.setStates(1);
collectorTaskMapper.update(task,new QueryWrapper<CollectorTask>().eq("XXL_JOB_ID",id));
return R.ok(jsonObject);
}
return R.failed(jsonObject);
} catch (Exception e) {
e.printStackTrace();
return R.failed(e.getMessage());
}
}
// 停止任務(wù)
@GetMapping("/stop")
public R stopTask(Integer id) {
try {
JSONObject jsonObject = XxlJobUtil.stopJob(xxlJobAdminHost, id);
if (jsonObject.getString("code").equals("200")) {
CollectorTask task = new CollectorTask();
task.setStates(0);
collectorTaskMapper.update(task,new QueryWrapper<CollectorTask>().eq("XXL_JOB_ID",id));
return R.ok(jsonObject);
} else {
return R.failed(jsonObject);
}
} catch (Exception e) {
e.printStackTrace();
return R.failed(e.getMessage());
}
}
// 獲取任務(wù)列表
@GetMapping("/getJobPage")
public R getJobPage(Integer pageSize,Integer pageNum,Integer jobId){
try {
return R.ok(XxlJobUtil.getPageList(jobId,pageSize,pageNum));
} catch (Exception e) {
e.printStackTrace();
return R.failed(e.getMessage());
}
}
// 調(diào)度任務(wù)記錄
// 獲取任務(wù)日志列表
@GetMapping("/getLogPage")
public R getLogPage(Integer pageSize,Integer pageNum,Integer jobId,String filterTime){
try {
return R.ok(XxlJobUtil.getLogPage(jobId, filterTime, (pageNum-1)*pageSize, pageSize));
} catch (Exception e) {
e.printStackTrace();
return R.failed(e.getMessage());
}
}
// 獲取任務(wù)
@GetMapping("/getJob")
public R getLogPage(Integer jobId){
try {
return R.ok(XxlJobUtil.getJobById(jobId));
} catch (Exception e) {
e.printStackTrace();
return R.failed(e.getMessage());
}
}
// 獲取任務(wù)日志詳情
@GetMapping("/getLogDetail")
public R getLogDetail(Integer logId,String executorAddress,Long triggerTime,Integer fromLineNum){
try {
return R.ok(XxlJobUtil.getLogDetailCat(logId, executorAddress, triggerTime, fromLineNum));
} catch (Exception e) {
e.printStackTrace();
return R.failed(e.getMessage());
}
}
}以上就是Java實(shí)現(xiàn)定時(shí)任務(wù)的示例代碼的詳細(xì)內(nèi)容,更多關(guān)于Java定時(shí)任務(wù)的資料請關(guān)注腳本之家其它相關(guān)文章!
相關(guān)文章
java通過AES生成公鑰加密數(shù)據(jù)ECC加密公鑰
這篇文章主要為大家介紹了java通過AES生成公鑰加密數(shù)據(jù)ECC加密公鑰實(shí)現(xiàn)案例詳解,有需要的朋友可以借鑒參考下,希望能夠有所幫助,祝大家多多進(jìn)步,早日升職加薪2022-12-12
IDEA對使用了第三方依賴jar包的非Maven項(xiàng)目打jar包的問題(圖文詳解)
這篇文章主要介紹了IDEA對使用了第三方依賴jar包的非Maven項(xiàng)目打jar包的問題,本文給大家介紹的非常詳細(xì),對大家的學(xué)習(xí)或工作具有一定的參考借鑒價(jià)值,需要的朋友可以參考下2020-07-07
java使用EasyExcel實(shí)現(xiàn)合并單元格
這篇文章主要為大家詳細(xì)介紹了java使用EasyExcel實(shí)現(xiàn)合并單元格的相關(guān)知識,文中的示例代碼講解詳細(xì),感興趣的小伙伴可以跟隨小編一起學(xué)習(xí)一下2023-12-12
mybatis-plus動態(tài)數(shù)據(jù)源讀寫分離方式
在分布式項(xiàng)目開發(fā)中,動態(tài)數(shù)據(jù)源的配置與使用至關(guān)重要,通過創(chuàng)建DynamicDatasourceService,實(shí)現(xiàn)數(shù)據(jù)源的動態(tài)添加與調(diào)用,有效管理主從庫操作,減輕數(shù)據(jù)庫壓力,此外,通過配置類與@DS注解,實(shí)現(xiàn)了靈活的分庫查詢功能,為高效處理數(shù)據(jù)提供了強(qiáng)有力的支持2024-10-10
Java泛型extends關(guān)鍵字設(shè)置邊界的實(shí)現(xiàn)
這篇文章主要介紹了Java泛型extends關(guān)鍵字設(shè)置邊界的實(shí)現(xiàn),文中通過示例代碼介紹的非常詳細(xì),對大家的學(xué)習(xí)或者工作具有一定的參考學(xué)習(xí)價(jià)值,需要的朋友們下面隨著小編來一起學(xué)習(xí)學(xué)習(xí)吧2019-09-09

