欧美bbbwbbbw肥妇,免费乱码人妻系列日韩,一级黄片

Java實現(xiàn)定時任務的示例代碼

 更新時間:2022年11月19日 11:20:34   作者:LLL_  
這篇文章主要為大家詳細介紹了Java實現(xiàn)定時任務的相關知識,文中示例代碼介紹的非常詳細,具有一定的參考價值,感興趣的小伙伴們可以參考一下

xxl-job官網(wǎng)

https://www.xuxueli.com/xxl-job/

調(diào)用xxl-job中的xxl-job-admin模塊啟用

引入依賴

<!--    調(diào)度任務    -->
        <dependency>
            <groupId>com.xuxueli</groupId>
            <artifactId>xxl-job-core</artifactId>
            <version>2.3.0</version>
        </dependency>

配置信息(application.properties)

### 調(diào)度中心部署根地址 [選填]:如調(diào)度中心集群部署存在多個地址則用逗號分隔。執(zhí)行器將會使用該地址進行"執(zhí)行器心跳注冊"和"任務結(jié)果回調(diào)";為空則關閉自動注冊;
xxl.job.admin.addresses=http://127.0.0.1:8883/xxl-job-admin
### 執(zhí)行器通訊TOKEN [選填]:非空時啟用;
xxl.job.accessToken=default_token
### 執(zhí)行器AppName [選填]:執(zhí)行器心跳注冊分組依據(jù);為空則關閉自動注冊
xxl.job.executor.appname=xxl-job-executor-sample
### 執(zhí)行器注冊 [選填]:優(yōu)先使用該配置作為注冊地址,為空時使用內(nèi)嵌服務 ”IP:PORT“ 作為注冊地址。從而更靈活的支持容器類型執(zhí)行器動態(tài)IP和動態(tài)映射端口問題。
xxl.job.executor.address=
### 執(zhí)行器IP [選填]:默認為空表示自動獲取IP,多網(wǎng)卡時可手動設置指定IP,該IP不會綁定Host僅作為通訊實用;地址信息用于 "執(zhí)行器注冊" 和 "調(diào)度中心請求并觸發(fā)任務";
xxl.job.executor.ip=
### 執(zhí)行器端口號 [選填]:小于等于0則自動獲?。荒J端口為9999,單機部署多個執(zhí)行器時,注意要配置不同執(zhí)行器端口;
xxl.job.executor.port=9999
### 執(zhí)行器運行日志文件存儲磁盤路徑 [選填] :需要對該路徑擁有讀寫權限;為空則使用默認路徑;
xxl.job.executor.logpath=/Users/linyanxia/Downloads/common/log/jobhandler
### 執(zhí)行器日志文件保存天數(shù) [選填] : 過期日志自動清理, 限制值大于等于3時生效; 否則, 如-1, 關閉自動清理功能;
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);

    }

    /**
     * 新增/編輯任務
     * @param url
     * @param requestInfo
     */
    public static JSONObject addJob(String url,Map requestInfo) throws Exception {
        String path = "/jobinfo/add";
        return doPost(url,path,requestInfo);
    }

    /**
     * 編輯任務
     * /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)度任務");
        }
        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("更新任務調(diào)度時間失敗");
        }
        return resultJson;
    }

    /**
     * 刪除任務
     * @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í)行任務
     * @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);

    }

    /**
     * 開始任務
     * @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);
    }



    /**
     * 停止任務
     * @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)度任務

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任務 {}",response);
        if (!response.getString("code").equals("200")){
            throw new Exception("新增任務調(diào)度失敗");
        }
//      獲取生成調(diào)度任務ID。根據(jù)此ID去執(zhí)行調(diào)度任務
        collectorTask.setXxlJobId(response.getInteger("content"));


//        刪除調(diào)度任務
        XxlJobUtil.deleteJob(task_id.getXxlJobId());

//        修改調(diào)度任務
        XxlJobUtil.editJobSchedule(collectorTask.getXxlJobId(),collectorTask.getDispatchTime());

調(diào)度任務

@RestController
@RequestMapping("/apiSyncTask")
public class ApiSyncTaskController {

    @Value("${xxl.job.admin.addresses}")
    private String xxlJobAdminHost;

    @Autowired(required = false)
    private CollectorTaskMapper collectorTaskMapper;

//    單次啟動任務
    @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());
        }
    }

//    啟動任務
    @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());
        }
    }

//    停止任務
    @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());
        }
    }

//    獲取任務列表
    @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)度任務記錄
//    獲取任務日志列表
    @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());
        }
    }

//    獲取任務
    @GetMapping("/getJob")
    public R getLogPage(Integer jobId){
        try {
            return R.ok(XxlJobUtil.getJobById(jobId));
        } catch (Exception e) {
            e.printStackTrace();
            return  R.failed(e.getMessage());
        }
    }

//    獲取任務日志詳情
    @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實現(xiàn)定時任務的示例代碼的詳細內(nèi)容,更多關于Java定時任務的資料請關注腳本之家其它相關文章!

相關文章

  • 顯示SonarQube私有項目徽章方案流程

    顯示SonarQube私有項目徽章方案流程

    這篇文章主要為大家介紹了如何顯示SonarQube私有項目徽章方案的流程,sonarQube目前不支持私有項目的徽章圖片獲取,這個問題早在?2018年就在sonar社區(qū)里有過激烈的討論,至今無果,只能自己尋求一種可以快速實施的方案
    2022-02-02
  • Java 滑動窗口最大值的實現(xiàn)

    Java 滑動窗口最大值的實現(xiàn)

    這篇文章主要介紹了Java 滑動窗口最大值,給定一個數(shù)組 nums,有一個大小為 k 的滑動窗口從數(shù)組的最左側(cè)移動到數(shù)組的最右側(cè)。感興趣的可以了解一下
    2021-05-05
  • java8版本base64加密解密的實例

    java8版本base64加密解密的實例

    下面小編就為大家分享一篇java8版本base64加密解密的實例,具有很好的參考價值,希望對大家有所幫助。一起跟隨小編過來看看吧
    2017-12-12
  • java通過AES生成公鑰加密數(shù)據(jù)ECC加密公鑰

    java通過AES生成公鑰加密數(shù)據(jù)ECC加密公鑰

    這篇文章主要為大家介紹了java通過AES生成公鑰加密數(shù)據(jù)ECC加密公鑰實現(xiàn)案例詳解,有需要的朋友可以借鑒參考下,希望能夠有所幫助,祝大家多多進步,早日升職加薪
    2022-12-12
  • IDEA對使用了第三方依賴jar包的非Maven項目打jar包的問題(圖文詳解)

    IDEA對使用了第三方依賴jar包的非Maven項目打jar包的問題(圖文詳解)

    這篇文章主要介紹了IDEA對使用了第三方依賴jar包的非Maven項目打jar包的問題,本文給大家介紹的非常詳細,對大家的學習或工作具有一定的參考借鑒價值,需要的朋友可以參考下
    2020-07-07
  • java使用EasyExcel實現(xiàn)合并單元格

    java使用EasyExcel實現(xiàn)合并單元格

    這篇文章主要為大家詳細介紹了java使用EasyExcel實現(xiàn)合并單元格的相關知識,文中的示例代碼講解詳細,感興趣的小伙伴可以跟隨小編一起學習一下
    2023-12-12
  • java開發(fā)技巧代碼寫的快且bug少的原因分析

    java開發(fā)技巧代碼寫的快且bug少的原因分析

    這篇文章主要為大家介紹了java開發(fā)中代碼寫的快且bug少的原因分析及技巧詳解,有需要的朋友可以借鑒參考下,希望能夠有所幫助,祝大家多多進步,早日升職加薪
    2022-12-12
  • 在Java中判斷兩個Long對象是否相等

    在Java中判斷兩個Long對象是否相等

    這篇文章主要介紹了在Java中判斷兩個Long對象是否相等的操作,具有很好的參考價值,希望對大家有所幫助。如有錯誤或未考慮完全的地方,望不吝賜教
    2021-07-07
  • mybatis-plus動態(tài)數(shù)據(jù)源讀寫分離方式

    mybatis-plus動態(tài)數(shù)據(jù)源讀寫分離方式

    在分布式項目開發(fā)中,動態(tài)數(shù)據(jù)源的配置與使用至關重要,通過創(chuàng)建DynamicDatasourceService,實現(xiàn)數(shù)據(jù)源的動態(tài)添加與調(diào)用,有效管理主從庫操作,減輕數(shù)據(jù)庫壓力,此外,通過配置類與@DS注解,實現(xiàn)了靈活的分庫查詢功能,為高效處理數(shù)據(jù)提供了強有力的支持
    2024-10-10
  • Java泛型extends關鍵字設置邊界的實現(xiàn)

    Java泛型extends關鍵字設置邊界的實現(xiàn)

    這篇文章主要介紹了Java泛型extends關鍵字設置邊界的實現(xiàn),文中通過示例代碼介紹的非常詳細,對大家的學習或者工作具有一定的參考學習價值,需要的朋友們下面隨著小編來一起學習學習吧
    2019-09-09

最新評論