最新国产好看的视频,伊人天堂AV在线,国产Aaaaaa视频,蜜臀视频在线观看一区,人妻av色图,密臀久久久精品影片,青青视频免费观看毛片,久草在线观看视,国产三级精品色情在线

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

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

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

相關(guān)文章

  • Java進(jìn)階教程之運行時類型識別RTTI機制

    Java進(jìn)階教程之運行時類型識別RTTI機制

    這篇文章主要介紹了Java進(jìn)階教程之運行時類型識別RTTI機制,在Java運行時,RTTI維護(hù)類的相關(guān)信息,比如多態(tài)(polymorphism)就是基于RTTI實現(xiàn)的,需要的朋友可以參考下
    2014-09-09
  • java中的JsonSerializer用法,前后端單位轉(zhuǎn)換必備

    java中的JsonSerializer用法,前后端單位轉(zhuǎn)換必備

    這篇文章主要介紹了java中的JsonSerializer用法,前后端單位轉(zhuǎn)換必備!具有很好的參考價值,希望對大家有所幫助。如有錯誤或未考慮完全的地方,望不吝賜教
    2021-10-10
  • springboot 自定義404、500錯誤提示頁面的實現(xiàn)

    springboot 自定義404、500錯誤提示頁面的實現(xiàn)

    springboot 默認(rèn)已經(jīng)提供了一套處理異常的機制。在 springboot 中提供了一個名為 BasicErrorController 的類來處理 /error 請求,然后跳轉(zhuǎn)到默認(rèn)顯示異常的頁面來展示異常信息,本文就詳細(xì)的介紹一下,感興趣的可以了解一下
    2021-11-11
  • spring依賴注入原理與用法實例分析

    spring依賴注入原理與用法實例分析

    這篇文章主要介紹了spring依賴注入原理與用法,結(jié)合實例形式分析了spring框架依賴注入的概念、原理、用法案例及相關(guān)操作注意事項,需要的朋友可以參考下
    2019-10-10
  • java 中ThreadLocal 的正確用法

    java 中ThreadLocal 的正確用法

    這篇文章主要介紹了java 中ThreadLocal 的正確用法的相關(guān)資料,需要的朋友可以參考下
    2017-03-03
  • 使用Postman傳遞arraylist數(shù)據(jù)給springboot方式

    使用Postman傳遞arraylist數(shù)據(jù)給springboot方式

    這篇文章主要介紹了使用Postman傳遞arraylist數(shù)據(jù)給springboot方式,具有很好的參考價值,希望對大家有所幫助。如有錯誤或未考慮完全的地方,望不吝賜教
    2021-12-12
  • SpringMVC 參數(shù)綁定相關(guān)知識總結(jié)

    SpringMVC 參數(shù)綁定相關(guān)知識總結(jié)

    這篇文章主要介紹了SpringMVC 參數(shù)綁定相關(guān)知識總結(jié),幫助大家更好的理解和學(xué)習(xí)使用SpringMVC,感興趣的朋友可以了解下
    2021-03-03
  • java中不同版本JSONObject區(qū)別小結(jié)

    java中不同版本JSONObject區(qū)別小結(jié)

    本文主要介紹了java中不同版本JSONObject區(qū)別小結(jié),文中通過示例代碼介紹的非常詳細(xì),對大家的學(xué)習(xí)或者工作具有一定的參考學(xué)習(xí)價值,需要的朋友們下面隨著小編來一起學(xué)習(xí)學(xué)習(xí)吧
    2025-02-02
  • spring boot ajax跨域的兩種方式

    spring boot ajax跨域的兩種方式

    java語言在多數(shù)時,會作為一個后端語言,為前端的php,node.js等提供API接口。這篇文章主要介紹了spring boot ajax跨域的兩種方式,非常不錯,具有參考借鑒價值,需要的朋友可以參考下
    2017-05-05
  • Java錯誤:進(jìn)行語法分析時已到達(dá)文件結(jié)尾的解決

    Java錯誤:進(jìn)行語法分析時已到達(dá)文件結(jié)尾的解決

    這篇文章主要介紹了Java錯誤:進(jìn)行語法分析時已到達(dá)文件結(jié)尾的解決方案,具有很好的參考價值,希望對大家有所幫助,如有錯誤或未考慮完全的地方,望不吝賜教
    2023-08-08

最新評論

通州市| 荔浦县| 应城市| 维西| 中牟县| 视频| 通州区| 高台县| 宜都市| 绿春县| 武山县| 绥滨县| 巴里| 老河口市| 库车县| 闵行区| 张家港市| 临沧市| 云和县| 青浦区| 邮箱| 甘南县| 嘉兴市| 三穗县| 惠来县| 获嘉县| 始兴县| 繁昌县| 贵州省| 遵义县| 徐水县| 呈贡县| 错那县| 杭州市| 商河县| 台南县| 密云县| 射洪县| 清远市| 眉山市| 湛江市|