Spring Boot integrates Xxl-job to achieve awesome scheduled tasks

Article directory

    • Why choose Xxl-job?
    • Start integrating Xxl-job
      • Step 1: Add dependencies
      • Step 2: Configure the data source
      • Step 3: Initialize database tables
      • Step 4: Configure Xxl-job
      • Step 5: Write scheduled tasks
      • Step 6: Start the project
      • Step 7: Access Xxl-job Admin
    • Expansion: dynamically add and delete tasks
    • Summarize


Welcome to the architecture design column~Spring Boot integrates Xxl-job to achieve awesome scheduled tasks

  • ☆* o(≧▽≦)o *☆Hi~I am IT·Chen Han
  • ?Blog homepage: IT·Chen Han’s blog
  • Column of this series of articles: Architecture design
  • Other columns: Java learning route, Java interview skills, Java practical projects, AIGC artificial intelligence, data structure learning
  • The author of the article has limited skills and level. If there are errors in the article, I hope everyone can correct them
  • Welcome everyone to pay attention!

In modern application development, scheduled tasks are an integral part. In order to manage and monitor these tasks more efficiently, we usually use some excellent scheduled task scheduling frameworks. Xxl-job is one of the well-received frameworks, which provides visual task management interface, distributed task scheduling, execution logging and other functions. This article will take you step by step to integrate Xxl-job in the Spring Boot project to create an awesome scheduled task system.

Why choose Xxl-job?

When choosing a scheduled task framework, we need to consider some key factors, and Xxl-job just meets these needs:

  1. Visual management interface: Xxl-job provides an intuitive and easy-to-use visual management interface, allowing us to easily manage and monitor scheduled tasks.

  2. Distributed task scheduling: For distributed systems, Xxl-job provides powerful distributed task scheduling capabilities, which can easily realize the distribution and execution of tasks in the cluster.

  3. Task execution log: Xxl-job supports the recording and viewing of task execution logs, which helps to timely discover and solve problems in task execution.

  4. Dynamic addition and deletion of tasks: Xxl-job allows dynamic addition and deletion of tasks at runtime without stopping the entire application.

Start integrating Xxl-job

Step 1: Add dependencies

First, add the Xxl-job dependency to the Spring Boot project. Add the following dependencies to the pom.xml file:

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

Step 2: Configure data source

Xxl-job requires the use of a database to store task information and execution logs. Add database configuration in the application.properties (or application.yml) file of the Spring Boot project:

# Database configuration
spring.datasource.driver-class-name=com.mysql.cj.jdbc.Driver
spring.datasource.url=jdbc:mysql://localhost:3306/xxl_job?useUnicode=true & amp;characterEncoding=UTF-8 & amp;autoReconnect=true & amp;serverTimezone=Asia/Shanghai
spring.datasource.username=root
spring.datasource.password=root

Step 3: Initialize database tables

Xxl-job provides an initialization script to create the necessary database tables. Create a file named xxl-job.sql in the resources directory with the following content:

--xxl-job.sql

CREATE TABLE `xxl_job_qrtz_lock` (
  `lock_name` varchar(64) COLLATE utf8mb4_unicode_ci NOT NULL,
  `lock_value` varchar(64) COLLATE utf8mb4_unicode_ci DEFAULT NULL,
  `lock_grant` varchar(64) COLLATE utf8mb4_unicode_ci DEFAULT NULL,
  `lock_thread` varchar(255) COLLATE utf8mb4_unicode_ci DEFAULT NULL,
  PRIMARY KEY (`lock_name`),
  UNIQUE KEY `idx_lock_name` (`lock_name`)
) ENGINE=InnoDB DEFAULT CHARSET=utf8mb4 COLLATE=utf8mb4_unicode_ci;

CREATE TABLE `xxl_job_qrtz_triggers` (
  `trigger_name` varchar(80) COLLATE utf8mb4_unicode_ci NOT NULL,
  `trigger_group` varchar(80) COLLATE utf8mb4_unicode_ci NOT NULL,
  `job_name` varchar(80) COLLATE utf8mb4_unicode_ci NOT NULL,
  `job_group` varchar(80) COLLATE utf8mb4_unicode_ci NOT NULL,
  `next_fire_time` bigint(13) DEFAULT NULL,
  `prev_fire_time` bigint(13) DEFAULT NULL,
  `priority` integer(11) DEFAULT NULL,
  `trigger_state` varchar(16) COLLATE utf8mb4_unicode_ci NOT NULL,
  `trigger_type` varchar(8) COLLATE utf8mb4_unicode_ci NOT NULL,
  `start_time` bigint(13) NOT NULL,
  `end_time` bigint(13) DEFAULT NULL,
  `calendar_name` varchar(255) COLLATE utf8mb4_unicode_ci DEFAULT NULL,
  `misfire_instr` integer(11) DEFAULT NULL,
  `job_data` blob,
  PRIMARY KEY (`trigger_name`,`trigger_group`),
  FOREIGN KEY (`job_name`,`job_group`) REFERENCES `xxl_job

_qrtz_jobs` (`job_name`,`job_group`) ON DELETE CASCADE
) ENGINE=InnoDB DEFAULT CHARSET=utf8mb4 COLLATE=utf8mb4_unicode_ci;

CREATE TABLE `xxl_job_qrtz_jobs` (
  `job_name` varchar(80) COLLATE utf8mb4_unicode_ci NOT NULL,
  `job_group` varchar(80) COLLATE utf8mb4_unicode_ci NOT NULL,
  `desc` varchar(100) COLLATE utf8mb4_unicode_ci DEFAULT NULL,
  `add_time` bigint(13) DEFAULT NULL,
  `update_time` bigint(13) DEFAULT NULL,
  `author` varchar(100) COLLATE utf8mb4_unicode_ci DEFAULT NULL,
  `alarm_email` varchar(100) COLLATE utf8mb4_unicode_ci DEFAULT NULL,
  `executor_route_strategy` varchar(10) COLLATE utf8mb4_unicode_ci DEFAULT NULL,
  `executor_handler` varchar(255) COLLATE utf8mb4_unicode_ci NOT NULL,
  `executor_param` varchar(512) COLLATE utf8mb4_unicode_ci DEFAULT NULL,
  `executor_block_strategy` varchar(10) COLLATE utf8mb4_unicode_ci DEFAULT NULL,
  `executor_fail_retry_count` int(11) DEFAULT NULL,
  `child_jobid` varchar(255) COLLATE utf8mb4_unicode_ci DEFAULT NULL,
  `trigger_status` varchar(10) COLLATE utf8mb4_unicode_ci DEFAULT NULL,
  PRIMARY KEY (`job_name`,`job_group`),
  KEY `idx_qrtz_jobs_group` (`job_group`),
  FOREIGN KEY (`job_group`) REFERENCES `xxl_job_qrtz_job_groups` (`job_group`) ON DELETE CASCADE
) ENGINE=InnoDB DEFAULT CHARSET=utf8mb4 COLLATE=utf8mb4_unicode_ci;

CREATE TABLE `xxl_job_qrtz_job_groups` (
  `job_group` varchar(80) COLLATE utf8mb4_unicode_ci NOT NULL,
  `desc` varchar(100) COLLATE utf8mb4_unicode_ci DEFAULT NULL,
  `add_time` bigint(13) DEFAULT NULL,
  `update_time` bigint(13) DEFAULT NULL,
  `author` varchar(100) COLLATE utf8mb4_unicode_ci DEFAULT NULL,
  PRIMARY KEY (`job_group`)
) ENGINE=InnoDB DEFAULT CHARSET=utf8mb4 COLLATE=utf8mb4_unicode_ci;

These are the database tables required by Xxl-job. They will store task information, execution logs and other related data.

Step 4: Configure Xxl-job

Add the relevant configuration of Xxl-job in the application.properties (or application.yml) file of the Spring Boot project:

#xxl-job configuration
xxl.job.admin.addresses=http://localhost:8080/xxl-job-admin
xxl.job.accessToken=
xxl.job.executor.appname=your-app-name
xxl.job.executor.address=http://localhost:8080/xxl-job-executor
xxl.job.executor.ip=
xxl.job.executor.port=0
xxl.job.executor.logpath=/data/applogs/xxl-job/jobhandler
xxl.job.executor.logretentiondays=3
  • xxl.job.admin.addresses: Access address of Xxl-job Admin, used for management tasks.
  • xxl.job.accessToken: Access token of Xxl-job Executor, used for simple authentication.
  • xxl.job.executor.appname: executor name, used to distinguish different executors.
  • xxl.job.executor.address: The address of the executor, usually the address of the current project.
  • xxl.job.executor.ip: executor IP address. If it is empty, the local IP will be obtained automatically.
  • xxl.job.executor.port: executor port, 0 represents a random port.
  • xxl.job.executor.logpath: Executor log path.
  • xxl.job.executor.logretentiondays: Number of days to retain executor logs.

Step 5: Write scheduled tasks

In the Spring Boot project, we need to create execution logic for scheduled tasks. First, create a task class that implements the IJobHandler interface:

import com.xxl.job.core.biz.model.ReturnT;
import com.xxl.job.core.handler.annotation.XxlJob;
import org.springframework.stereotype.Component;

@Component
public class MyJobHandler {<!-- -->

    @XxlJob("myJobHandler")
    public ReturnT<String> myJobHandler(String param) {<!-- -->
        //Task logic code
        System.out.println("Scheduled task execution, parameters: " + param);
        return ReturnT.SUCCESS;
    }
}

This task class has a method myJobHandler marked with the @XxlJob annotation. This method is our scheduled task logic. Parameter param is the parameter of the scheduled task.

Step 6: Start the project

Now, you can start the Spring Boot project. When the project is started, Xxl-job Executor will automatically be registered in Admin, and scheduled tasks will be executed at the specified time.

Step 7: Access Xxl-job Admin

Open the browser and visit the address of Xxl-job Admin (default is http://localhost:8080/xxl-job-admin). On the interface, you will see a clear task management interface where you can add, edit and monitor tasks.

Expansion: dynamically add and delete tasks

Xxl-job provides an API that allows tasks to be dynamically added and removed at runtime. In practical applications, we may need to dynamically adjust tasks according to business needs without stopping the entire application.

The following is a simple example that demonstrates how to add a task using Xxl-job’s API:

import com.xxl.job.core.biz.model.ReturnT;
import com.xxl.job.core.handler.annotation.XxlJob;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;

@Component
public class DynamicJobHandler {<!-- -->

    @Autowired
    private XxlJobService xxlJobService;

    @XxlJob("dynamicJobHandler")
    public ReturnT<String> dynamicJobHandler(String param) {<!-- -->
        //Task logic code
        System.out.println("Dynamic scheduled task execution, parameters:" + param);
        return ReturnT.SUCCESS;
    }

    //Dynamicly add tasks
    public void addDynamicJob() {<!-- -->
        XxlJobInfo jobInfo = new XxlJobInfo```java
        .setJobGroup("YOUR_JOB_GROUP")
        .setJobDesc("Dynamic Task Example")
        .setExecutorRouteStrategy(ExecutorRouteStrategyEnum.FIRST.name())
        .setExecutorHandler("dynamicJobHandler")
        .setExecutorParam("parameter")
        .setExecutorBlockStrategy(ExecutorBlockStrategyEnum.SERIAL_EXECUTION.name())
        .setExecutorFailRetryCount(3);

    ReturnT<String> addResult = xxlJobService.addJob(jobInfo);
    if (addResult.getCode() == ReturnT.SUCCESS_CODE) {<!-- -->
        System.out.println("Dynamic task added successfully, JobId:" + addResult.getContent());
    } else {<!-- -->
        System.out.println("Dynamic task addition failed, error message:" + addResult.getMsg());
    }
}

//Dynamicly delete tasks
public void removeDynamicJob(int jobId) {<!-- -->
    ReturnT<String> removeResult = xxlJobService.removeJob(jobId);
    if (removeResult.getCode() == ReturnT.SUCCESS_CODE) {<!-- -->
        System.out.println("Dynamic task deleted successfully");
    } else {<!-- -->
        System.out.println("Dynamic task deletion failed, error message:" + removeResult.getMsg());
    }
}

In this example, we create a DynamicJobHandler class that contains a dynamic task dynamicJobHandler. By calling the xxlJobService.addJob method, we can dynamically add tasks. Likewise, tasks can be removed dynamically by calling the xxlJobService.removeJob method. In this way, we can flexibly manage tasks as needed while the application is running.

Summary

Through the introduction of this article, you have learned how to integrate Xxl-job in the Spring Boot project and implement awesome scheduled tasks. Xxl-job provides rich functions and a visual management interface, making the development and management of scheduled tasks easier. The ability to add and remove tasks dynamically also gives us greater flexibility.

I hope this article will help you understand and use Xxl-job. Timing tasks are an important component that every application may involve. It is very important to choose a timing task framework that suits your project. Considering Xxl-job’s ease of use and powerful functions, I believe it will be your best choice for scheduled tasks.

End Thank you for your support and encouragement!
Content you may be interested in:

  • [Java Interview Skills] Java Interview Eight-Part Essay – Mastering the Essential Knowledge for Interviews (Contents)
  • [Java Learning Roadmap] 2023 Full Version Java Learning Roadmap
  • [AIGC Artificial Intelligence] What is Chat GPT? How do beginners use Chat GPT? What should you pay attention to?
  • [Java Practical Project] SpringBoot + SSM Practical: Create an efficient and convenient enterprise-level Java takeout ordering system
  • [Data Structure Learning] Starting from Scratch: The Complete Path to Learning Data Structures