Xl-job is the first part of ElasticJob, and the first part of xL-Job is the first part of xxL-Job.

1. xxl-job

Songgo also discussed whether they use XXl-job or ElasticJob in his wechat group. The result of the discussion was that xxL-job was used by more people.

Regardless of the pros and cons of the features, we can actually see some clues from the data:

Here’s GitHub for xxL-job:

This is GitHub for ElasticJob:

From this data comparison, it can be seen that XXL-job is more popular. Note that XXl-job is hotter, not stronger than ElasticJob.

Xxl-job comes from Dianping, which is a distributed and lightweight task scheduling framework. Its core design goal is rapid development, simple learning, lightweight and easy to expand.

Xxl-job uses a centralized scheduling platform to schedule multiple actuators to execute tasks. The scheduling center ensures the consistency of distributed scheduling in the cluster through DB locks. In this way, expanding the actuators will increase the pressure on the DB. Xxl-job provides a very useful monitoring page and even an email alarm function for task failure. Unlike ElasticJob, xxl-Job relies on MySQL and does not require ZooKeeper.

ElasticJob is created by Dangdang. The ElasticJob is designed to make full use of server resources even when there are a large number of services and a large number of servers. ElasticJob is decentralized. If the primary server fails, a new primary server is automatically elected using the Election mechanism of ZooKeeper. Therefore, ElasticJob has good scalability and availability.

So, which one are you going to use?

2. Run the XXL – job

Let’s run xxl-job first, and then write our own code.

Xxl-job = xxL-job = xxL-job

  • Github.com/xuxueli/xxl…

Then open the project with IDEA. After opening the project, there are four main folders:

  • Doc: Project documentation
  • Xxl-job-admin: indicates the task scheduling platform
  • Xxl-job-core: indicates the core code
  • XXL – job – executor – samples: case

Mysql > configure the database. Locate the database script in doc/db/tables_xxl_job. SQL.

After finding the database script, import it into the database and execute it. After executing it, generate the following libraries and tables:

Then find the XXL – job – admin/SRC/main/resources/application. The properties file, modify the database connection information:

spring.datasource.url=JDBC: mysql: / / 127.0.0.1:3306 / xxl_job? useUnicode=true&characterEncoding=UTF-8&autoReconnect=true&serverTimezone=Asia/Shanghai
spring.datasource.username=root
spring.datasource.password=123
spring.datasource.driver-class-name=com.mysql.cj.jdbc.Driver
Copy the code

Logging configuration also want to change, the XXL – job – admin/SRC/main/resources/logback. XML file, have the following line:

<property name="log.path" value="/data/applogs/xxl-job/xxl-job-admin.log"/>
Copy the code

If you are a Windows operating system, this will definitely change, and if you are a Mac, you may not have access to this directory, so I recommend you to change this configuration to something like this:

<property name="log.path" value="./applogs/xxl-job/xxl-job-admin.log"/>
Copy the code

Generate the log file in the project run directory instead.

After that, we can start the xxl-job-admin project, which is a SpringBoot project. Find the boot class and run its main method.

After the success of the project started, browser to enter the following address, http://localhost:8080/xxl-job-admin/toLogin, you can see the login page:

The default login account is admin/123456.

If you see the following page, you have logged in successfully.

3. Develop scheduled tasks

3.1 Project creation and configuration

Now let’s create a project and run a timed task.

Start by creating a SpringBoot project to introduce Web dependencies as follows:

After the project is successfully created, the dependency of xxl-job is introduced:

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

Add logback.xml to the resources directory as follows:


      
<configuration debug="false" scan="true" scanPeriod="1 seconds">

    <contextName>logback</contextName>
    <property name="log.path" value="./applogs/xxl-job/xxl-job-executor-sample-springboot.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

Modify the application.properties file as follows:

# web port
server.port=8089
# log configuration
logging.config=classpath:logback.xml
Configure the address of the dispatch center
xxl.job.admin.addresses=http://127.0.0.1:8080/xxl-job-admin
# Communication token between the executor and the dispatch center. If not configured, communication token verification is disabled.
# xxl-job-admin = xxl-job-admin = xxl-job-admin = xxl-job-admin = xxl-job-admin;
xxl.job.accessToken=
Configure the name of the actuator
xxl.job.executor.appname=xxl-job-demo
If not specified, IP:PORT is used as the default
xxl.job.executor.address=
IP address of the actuator
xxl.job.executor.ip=
# executor port, default is 9999
xxl.job.executor.port=9999
# executor log file location
xxl.job.executor.logpath=./applogs/xxl-job/jobhandler
# executor log save time
xxl.job.executor.logretentiondays=30
Copy the code

I have commented out the meanings of the configurations.

Next, a configuration class is provided as follows:

@Configuration
public class XxlJobConfig {
    private Logger logger = LoggerFactory.getLogger(XxlJobConfig.class);

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

    @Value("${xxl.job.accessToken}")
    private String accessToken;

    @Value("${xxl.job.executor.appname}")
    private String appname;

    @Value("${xxl.job.executor.address}")
    private String address;

    @Value("${xxl.job.executor.ip}")
    private String ip;

    @Value("${xxl.job.executor.port}")
    private int port;

    @Value("${xxl.job.executor.logpath}")
    private String logPath;

    @Value("${xxl.job.executor.logretentiondays}")
    private int logRetentionDays;


    @Bean
    public XxlJobSpringExecutor xxlJobExecutor(a) {
        logger.info(">>>>>>>>>>> xxl-job config init.");
        XxlJobSpringExecutor xxlJobSpringExecutor = new XxlJobSpringExecutor();
        xxlJobSpringExecutor.setAdminAddresses(adminAddresses);
        xxlJobSpringExecutor.setAppname(appname);
        xxlJobSpringExecutor.setAddress(address);
        xxlJobSpringExecutor.setIp(ip);
        xxlJobSpringExecutor.setPort(port);
        xxlJobSpringExecutor.setAccessToken(accessToken);
        xxlJobSpringExecutor.setLogPath(logPath);
        xxlJobSpringExecutor.setLogRetentionDays(logRetentionDays);
        returnxxlJobSpringExecutor; }}Copy the code

Properties as an XxlJobSpringExecutor Bean. I’m surprised you didn’t make it an automatic configuration Bean.

Now we can create a specific timed task.

3.2 Scheduled task development mode

For us Java engineers, there are three ways to develop scheduled tasks.

3.2.1 BEAN Mode (Class Form)

Bean-mode tasks that support class-based development, with one Java class for each task.

Advantages: not limited project environment, good compatibility. Even frameless projects, such as those launched directly with the main method, can be supported.

Disadvantages:

  • Each task requires one Java class, resulting in a waste of classes;
  • Automatic scan tasks are not supported and injected into the actuator container. Manual injection is required.

Development mode:

  1. Develop an inheritance fromcom.xxl.job.core.handler.IJobHandlerThe JobHandler class, which implements the task method.
  2. Manually inject into the actuator container as follows:
XxlJobExecutor.registJobHandler("demoJobHandler", new DemoJobHandler());
Copy the code
  1. Create a new scheduling task in the scheduling center (subsequent steps and3.2.1 BEAN Mode (Method form)).

This method is not used much, I will not show you, friends can try their own.

3.2.2 BEAN Mode (method form)

Bean-mode tasks, which support method-based development with one method for each task, are generally recommended.

Advantages:

  • You only need to develop one method for each task and add the annotation “@xxlJob” to make it easier and faster.
  • Supports automatic scanning tasks and injection into the actuator container.

Disadvantages:

  • A Spring container environment is required.

For method-based tasks, the underlying JobHandler agent is generated, and as with class-based tasks, the task exists in the executor task container as JobHandler.

Development steps:

  1. Developing Job methods:
@Component
public class MyJob {
    @XxlJob("demoJobHandler")
    public ReturnT<String> demoJobHandler(a) throws Exception {
        String param = XxlJobHelper.getJobParam();
        XxlJobHelper.log("Xxl-job, Hello World: {}",param);
        returnReturnT.SUCCESS; }}Copy the code

The @xxlJob annotation here marks this as a timed task method, and it also has init and destroy properties that configure the initialization and destroy methods, respectively.

Xxljobhelper.getjobparam () can be used to get job parameters.

In this process, we need to print the execution log through xxljobhelper. log.

The default task result is Succeeded and you do not need to actively set the task. If there are any demands, such as setting up task results for failure, can pass XxlJobHelper. HandleFail/handleSuccess setting the task results.

Then start the SpringBoot project.

  1. Configure the scheduling center and create a scheduling task

Next, open the Configuration Scheduling Center, find the executor Management, and click Add as follows:

For automatic registration, there is no need to fill in the machine address.

Next go to Task Management and click Add:

There’s nothing to say about the basic configuration.

Select CRON expression for scheduling type. CRON expression can be filled in by itself or generated automatically by clicking the edit button behind.

The run mode is BEAN. The JobHandler value is the same as the @xxlJob annotation, and the task parameter is the method parameter of the scheduled task.

After the configuration is complete, go back to the actuator management and click View to view the information of the newly registered node:

Go back to task management and select Start to start scheduled task execution:

After this function is enabled, click scheduling Log, you can see the detailed information of our system task execution:

As you can see, this is done every 5 seconds.

Click on scheduling remarks to view some scheduling details:

Select the execution log from the right operation button:

You can view the execution details:

The one in red is the one we just printed ourselves.

Of course, there are some other ways that you can click on the button to try, but I won’t go into that.

3.2.3 GLUE Mode (Java)

Tasks are maintained in the dispatch center in source code and are updated online via the Web IDE, compiled and executed in real time, so there is no need to specify JobHandler. Write code for a scheduled task on a web page and then execute it.

This way of personal feeling less use, partners can understand.

The development process is as follows:

  1. Scheduling Center -> Task Management to create a scheduling task, select GLUE mode (Java).

  1. Develop task code: Select the specified task and click the GLUE button on the right of the task to go to the Web IDE interface of the GLUE task, where the task code can be developed (you can also copy and paste it into the edit after the development is completed in the IDE).

After editing, save it. Again, start the task and then view the scheduling log.

Version backtracking of 30 versions is supported. On the Web IDE interface of the GLUE task, select Version Backtracking in the upper right corner to list the update history of the GLUE. Select the corresponding version to display the code of the GLUE version.

4. Summary

That’s what I’m trying to say about xxL-job

You can download the case of this article from xxl-job-demo.