Xxl-job Distributed task scheduling platform

Initializing the database

Execute the SQL provided by the official

/xxl-job/doc/db/tables_xxl_job.sql
Copy the code

The source code to compile

xuxueli/xxl-job

After downloading the source code, you need to modify some configurations

Xxl-job-admin: scheduling center xxl-job-core: common dependencies XXl-job-executor-samples: executor Sample (select the appropriate version executor, which can be used directly, or refer to it and transform an existing project into an executor) : Xxl-job-executor-sample-springboot: indicates the springboot version. You are advised to use springboot to manage actuators. : xxl-job-executor-sample-frameless: no frame version;Copy the code

Because the deployment is direct, you only need to modify the configuration of the scheduling center

### xxl-job, datasource spring.datasource.url=jdbc:mysql://localhost:3306/xxl_job? useUnicode=true&characterEncoding=UTF-8&autoReconnect=true&serverTimezone=Asia/Shanghai spring.datasource.username=guest  spring.datasource.password=123456 spring.datasource.driver-class-name=com.mysql.cj.jdbc.Driver ### xxl-job, email spring.mail.host=smtp.qq.com spring.mail.port=25 [email protected] spring.mail.password=yltkhbpxjeacbbfj spring.mail.properties.mail.smtp.auth=true spring.mail.properties.mail.smtp.starttls.enable=true spring.mail.properties.mail.smtp.starttls.required=true spring.mail.properties.mail.smtp.socketFactory.class=javax.net.ssl.SSLSocketFactoryCopy the code

Installing the Dispatch Center

Deployment project

java -jar xxx &
Copy the code

http://localhost:8080/xxl-job-admin

Account: Password admin/123456

Develop your own tasks

There are detailed tutorials on the official website

Xxl-job Distributed task scheduling platform

Rely on

compile group: 'com.xuxueli', name: 'xxl-job-core'
Copy the code

configuration

### xxl-job admin address list, such as "http://address" or "http://address01,http://address02" XXL. Job. Admin. Addresses = http://127.0.0.1:18301/xxl-job-admin # # # XXL - job, access token xxl.job.accessToken= ### xxl-job executor appname xxl.job.executor.appname=pension-job ### xxl-job executor  registry-address: default use address to registry , otherwise use ip:port if address is null xxl.job.executor.address= ### xxl-job executor server-info xxl.job.executor.ip=  xxl.job.executor.port=9999 ### xxl-job executor log-path xxl.job.executor.logpath=/data/applogs/xxl-job/jobhandler ### xxl-job executor log-retention-days xxl.job.executor.logretentiondays=30Copy the code

Timing method

package com.fedtech.job.provider.service.jobHandler; import com.xxl.job.core.biz.model.ReturnT; import com.xxl.job.core.handler.IJobHandler; import com.xxl.job.core.handler.annotation.XxlJob; import com.xxl.job.core.log.XxlJobLogger; import com.xxl.job.core.util.ShardingUtil; import lombok.extern.slf4j.Slf4j; import org.slf4j.Logger; import org.slf4j.LoggerFactory; import org.springframework.stereotype.Component; import java.io.BufferedInputStream; import java.io.BufferedReader; import java.io.DataOutputStream; import java.io.InputStreamReader; import java.net.HttpURLConnection; import java.net.URL; import java.util.Arrays; import java.util.concurrent.TimeUnit; /** * XxlJob; /** * XxlJob; * <p>"public ReturnT<String> execute(String param)"* 2. Add annotations to the Job method"@XxlJob(value="User-defined jobHandler name", init = "JobHandler Initialization method", destroy = "JobHandler Destruction method")"The annotation value corresponds to the value of the JobHandler property for the new task in the dispatch center. * 3. Execution log: Yes"XxlJobLogger.log"The execution log is displayed. ** @component @slf4j public class SampleXxlJob {/** * @XxlJob("demoJobHandler")
    public ReturnT<String> demoJobHandler(String param) throws Exception {
        XxlJobLogger.log("XXL-JOB, Hello World.");

        for (int i = 0; i < 5; i++) {
            XxlJobLogger.log("beat at:" + i);
            TimeUnit.SECONDS.sleep(2);
        }
        returnReturnT.SUCCESS; } /** * 1;"shardingJobHandler") public ReturnT<String> shardingJobHandler(String param) throws Exception {// Sharding parameter shardingutil. ShardingVO ShardingVO = ShardingUtil.getShardingVo(); XxlJobLogger.log("Shard parameter: Current shard number = {}, total shard number = {}", shardingVO.getIndex(), shardingVO.getTotal()); // Business logicfor (int i = 0; i < shardingVO.getTotal(); i++) {
            if (i == shardingVO.getIndex()) {
                XxlJobLogger.log({} slice, hit fragment start processing, i);
            } else {
                XxlJobLogger.log("{} slice, ignore", i); }}returnReturnT.SUCCESS; } /** * 3, */ @xxljob ("commandJobHandler")
    public ReturnT<String> commandJobHandler(String param) throws Exception {
        String command = param;
        int exitValue = -1;

        BufferedReader bufferedReader = null;
        try {
            // command process
            Process process = Runtime.getRuntime().exec(command);
            BufferedInputStream bufferedInputStream = new BufferedInputStream(process.getInputStream());
            bufferedReader = new BufferedReader(new InputStreamReader(bufferedInputStream));

            // command log
            String line;
            while((line = bufferedReader.readLine()) ! = null) { XxlJobLogger.log(line); } / /command exit
            process.waitFor();
            exitValue = process.exitValue();
        } catch (Exception e) {
            XxlJobLogger.log(e);
        } finally {
            if (bufferedReader != null) {
                bufferedReader.close();
            }
        }

        if (exitValue == 0) {
            return IJobHandler.SUCCESS;
        } else {
            return new ReturnT<String>(IJobHandler.FAIL.getCode(), "command exit value(" + exitValue + ") is failed"); }} /** * 4, cross-platform Http task * parameter example: *"url: http://www.baidu.com\n" +
     * "method: get\n" +
     * "data: content\n";
     */
    @XxlJob("httpJobHandler")
    public ReturnT<String> httpJobHandler(String param) throws Exception {

        // param parse
        if (param == null || param.trim().length() == 0) {
            XxlJobLogger.log("param[" + param + "] invalid.");
            return ReturnT.FAIL;
        }
        String[] httpParams = param.split("\n");
        String url = null;
        String method = null;
        String data = null;
        for (String httpParam : httpParams) {
            if (httpParam.startsWith("url:")) {
                url = httpParam.substring(httpParam.indexOf("url:") + 4).trim();
            }
            if (httpParam.startsWith("method:")) {
                method = httpParam.substring(httpParam.indexOf("method:") + 7).trim().toUpperCase();
            }
            if (httpParam.startsWith("data:")) {
                data = httpParam.substring(httpParam.indexOf("data:") + 5).trim();
            }
        }

        // param valid
        if (url == null || url.trim().length() == 0) {
            XxlJobLogger.log("url[" + url + "] invalid.");
            return ReturnT.FAIL;
        }
        if(method == null || ! Arrays.asList("GET"."POST").contains(method)) {
            XxlJobLogger.log("method[" + method + "] invalid.");
            return ReturnT.FAIL;
        }

        // request
        HttpURLConnection connection = null;
        BufferedReader bufferedReader = null;
        try {
            // connection
            URL realUrl = new URL(url);
            connection = (HttpURLConnection) realUrl.openConnection();

            // connection setting
            connection.setRequestMethod(method);
            connection.setDoOutput(true);
            connection.setDoInput(true);
            connection.setUseCaches(false);
            connection.setReadTimeout(5 * 1000);
            connection.setConnectTimeout(3 * 1000);
            connection.setRequestProperty("connection"."Keep-Alive");
            connection.setRequestProperty("Content-Type"."application/json; charset=UTF-8");
            connection.setRequestProperty("Accept-Charset"."application/json; charset=UTF-8");

            // do connection
            connection.connect();

            // data
            if(data ! = null && data.trim().length() > 0) { DataOutputStream dataOutputStream = new DataOutputStream(connection.getOutputStream()); dataOutputStream.write(data.getBytes("UTF-8"));
                dataOutputStream.flush();
                dataOutputStream.close();
            }

            // valid StatusCode
            int statusCode = connection.getResponseCode();
            if(statusCode ! = 200) { throw new RuntimeException("Http Request StatusCode(" + statusCode + ") Invalid.");
            }

            // result
            bufferedReader = new BufferedReader(new InputStreamReader(connection.getInputStream(), "UTF-8"));
            StringBuilder result = new StringBuilder();
            String line;
            while((line = bufferedReader.readLine()) ! = null) { result.append(line); } String responseMsg = result.toString(); XxlJobLogger.log(responseMsg);return ReturnT.SUCCESS;
        } catch (Exception e) {
            XxlJobLogger.log(e);
            return ReturnT.FAIL;
        } finally {
            try {
                if(bufferedReader ! = null) { bufferedReader.close(); }if(connection ! = null) { connection.disconnect(); } } catch (Exception e2) { XxlJobLogger.log(e2); }}} /** * 5, life cycle task example: task initialization and destruction, support custom related logic; */ @XxlJob(value ="demoJobHandler2", init = "init", destroy = "destroy")
    public ReturnT<String> demoJobHandler2(String param) throws Exception {
        XxlJobLogger.log("XXL-JOB, Hello World.");
        return ReturnT.SUCCESS;
    }

    public void init() {
        log.info("init");
    }

    public void destroy() {
        log.info("destory"); }}Copy the code

A new task

Parameter configuration

perform

Click the execute button

See the log

By yong-sheng zhu