This is my fourth day of the August Genwen Challenge

preface

Hi, everybody, I’m Helu.

In the last article, we introduced several ways to create a scheduled task. How to create a scheduled task in Java? , introduced the use of Quartz framework to create scheduled task scheduling in distributed environment, but this approach has obvious disadvantages, although Quartz can achieve high availability of jobs based on the database, but it lacks the function of distributed parallel scheduling, and does not solve the problem of task fragmentation, can not achieve horizontal expansion. Not suitable for large distributed projects.

Today’s article introduces another way to create a scheduled task schedule in a distributed environment, using the XXl-Job framework. If the article is helpful to you, don’t forget to like and forward support, thank you! The source code is attached at the end of the article

What is xxL-job?

Xxl-job is a lightweight distributed task scheduling framework. Its core design objective is rapid development, simple learning, lightweight and easy to expand, which is mainly divided into two parts: scheduling center and executor. Scheduling center generates RPC proxy object (HTTP protocol call) of executor by default when starting initialization. After the executor project starts, The dispatch center invokes the code in the executor project through jobHandle after triggering the timer.

Advantages: Lightweight, supports cluster deployment, provides a complete GRAPHICAL user interface (GUI), and supports advanced functions such as elastic capacity expansion, distributed broadcast, and failover.

Disadvantages: The scheduling center obtains DB locks to ensure the uniqueness of tasks to be executed in the cluster. If there are many short tasks, as the number of scheduling center clusters increases, database lock competition increases, resulting in performance deterioration.

Two, the use of steps

1. Download and import the source code

Github download: github.com/xuxueli/xxl…

Gitee download: gitee.com/xuxueli0323…

2. Execute SQL

Run the SQL script in db

3. Modify the xxl-job-admin configuration

The default port number is 8080. You can also change the appropriate port number. I changed the port number to 8002.

4. Start the admin project

Start the project

accesshttp://localhost:8002/xxl-job-admin/Account password: admin / 123456At this point, the task control center is set up.

5. Create a self-created sample task demo

5.1 Adding a Dependency

Create a SpringBoot project and add xxl-job dependencies

<dependency>
	<groupId>com.xuxueli</groupId>
	<artifactId>xxl-job-core</artifactId>
	<version>2.3.0</version>
</dependency>
Copy the code

5.2 Log Configuration

Add a log configuration file

<? xml version="1.0" encoding="UTF-8"? ><configuration debug="false" scan="true" scanPeriod="1 seconds">

    <contextName>logback</contextName>
    <property name="log.path" value="/data/applogs/xxl-job/xxl-job-admin.log"/>

    <appender name="console" class="ch.qos.logback.core.ConsoleAppender">
        <encoder>
            <pattern>%d{HH:mm:ss.SSS} %contextName [%thread] %-5level %logger{36} - %msg%n</pattern>
        </encoder>
    </appender>

    <appender name="file" class="ch.qos.logback.core.rolling.RollingFileAppender">
        <file>${log.path}</file>
        <rollingPolicy class="ch.qos.logback.core.rolling.TimeBasedRollingPolicy">
            <fileNamePattern>${log.path}.%d{yyyy-MM-dd}.zip</fileNamePattern>
        </rollingPolicy>
        <encoder>
            <pattern>%date %level [%thread] %logger{36} [%file : %line] %msg%n
            </pattern>
        </encoder>
    </appender>

    <root level="info">
        <appender-ref ref="console"/>
        <appender-ref ref="file"/>
    </root>

</configuration>
Copy the code

5.3 Properties File Modification

Application.properties adds the configuration

Xxl-job admin address xxl.job.executor. Appname User-defined name. The background configuration must correspond to xxl.job.executor. Or the COMPUTER Ip xxl.job.executor.port of the deployment project

Server.port =8081Config =classpath:logback. XML ### XXL -job admin address, separated by multiple commas"XXL. Job. Admin. Addresses = http://127.0.0.1:8002/xxl-job-admin # # # XXL - job name | | IP socket the IP address of the current project deployment/native IP | | socket to port number IP =127.0.0.1 xxl.job.executor.port=9999 ### xxl-job, access token xxl.job.accessToken= ### xxl-job log path xxl.job.executor.logpath=/data/applogs/xxl-job/jobhandler ### xxl-job log retention days xxl.job.executor.logretentiondays=-1Copy the code

5.4 Adding a Config Configuration Class

@Configuration
public class XxlJobConfig {

    Logger logger = LoggerFactory.getLogger(XxlJobConfig.class);

    @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(initMethod = "start", destroyMethod = "destroy")
    public XxlJobSpringExecutor xxlJobExecutor() {
        logger.info(">>>>>>>>>>> xxl-job xxljob.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);
        logger.info(ip+":"+port);
        returnxxlJobSpringExecutor; }}Copy the code

5.5 Writing A Task Job

@Component
public class DemoJobHandler {

    static int count = 0;

    @XxlJob("demoJobHandler")
    public void execute(String param) throws Exception {
        System.out.println("Hello,demoJobHandler executes job task"+ count++); }}Copy the code

6. Admin Background configuration

The admin page is displayed to configure related tasks. Let’s add an actuator

Create a task in task Management and configure a time policy for the task. I configured a policy to execute every 5 seconds.

When the configuration is complete, click Start

You can successfully log job execution on the console of the sample demo project, and you’re done.

conclusion

Ok, that’s it for today. Thanks for reading, and if you have any questions or suggestions, feel free to leave them in the comments section

Demo source code:

Gitee address

Making the address