当前位置:网站首页>Initial experience of using XXL job
Initial experience of using XXL job
2022-06-10 05:18:00 【Focus on writing bugs】
List of articles
Preface
In project development , About the creation of scheduled tasks , There are many ways , The most common use is Springboot Encapsulated in the framework @EnableScheduling.
In monomer applications ,Schedualed It can perfectly realize the function of timed tasks , But with the upgrading of the system and the surge of traffic . The architecture of the project needs to expand and develop in the distributed direction , If you continue to use schedualed Implement scheduled task operation , It often leads to Some tasks are repeated Other questions , There are many disadvantages .
xxl-job Belong to Distributed Of Scheduling platform , It can perfectly solve the above problems .
Extend several scheduled tasks to create
SpringBoot Achieve timed tasks
stay Springboot In the project , It comes with it @Scheduled Start scheduled task .
Only need Start class Top annotation @EnableScheduling, At the same time, appropriate Cron expression Can achieve . As shown below :

When the program runs , The console will display the following log information :
quartz-job Create a scheduled task
Depend on the introduction of :
<dependencies>
<!-- https://mvnrepository.com/artifact/org.quartz-scheduler/quartz -->
<dependency>
<groupId>org.quartz-scheduler</groupId>
<artifactId>quartz</artifactId>
<version>2.2.1</version>
</dependency>
<!-- https://mvnrepository.com/artifact/org.quartz-scheduler/quartz-jobs -->
<dependency>
<groupId>org.quartz-scheduler</groupId>
<artifactId>quartz-jobs</artifactId>
<version>2.2.1</version>
</dependency>
</dependencies>
Test code writing
package cn.xj;
import org.quartz.Job;
import org.quartz.JobExecutionContext;
import org.quartz.JobExecutionException;
/** * Realization Job Interface , rewrite execute Method */
public class QuartzDemo implements Job {
/** * Execute the logic of task scheduling * @param jobExecutionContext * @throws JobExecutionException */
@Override
public void execute(JobExecutionContext jobExecutionContext) throws JobExecutionException {
System.out.println("6666666");
}
}
package cn.xj;
import org.quartz.*;
import org.quartz.impl.StdSchedulerFactory;
import java.util.Date;
/** * quartz-job The test class */
public class Test {
public static void main(String[] args) throws SchedulerException {
// 1、 establish scheduled factory
StdSchedulerFactory stdSchedulerFactory = new StdSchedulerFactory();
// 2、 Get an instance of the scheduler from the factory
Scheduler scheduler = stdSchedulerFactory.getScheduler();
// 3、 establish JobDetail
JobDetail job = JobBuilder.newJob(QuartzDemo.class)
.withDescription("xiangjiao test") // job describe
.withIdentity("xiangjiao", "bunana") // name and group
.build();
// Task execution time , The trigger etc.
long startTimes = System.currentTimeMillis()+3*1000L;
Date startDate = new Date(startTimes);
// 4、 establish CronTrigger
CronTrigger cronTrigger = TriggerBuilder.newTrigger()
.withDescription("this is a cronTrigger")
.withIdentity("xiangjiao2", "test2")
.startAt(startDate)
// Use SimpleScheduleBuilder perhaps CronScheduleBuilder
//.withSchedule(SimpleScheduleBuilder.simpleSchedule())
.withSchedule(CronScheduleBuilder.cronSchedule("0/5 * * * * ?")) // Every time 5 Once per second
.build();
// 5、 Register tasks and timers
scheduler.scheduleJob(job,cronTrigger);
// 6、 start-up Timing scheduler
scheduler.start();
// 7、 Turn off the scheduler
// scheduler.shutdown();
}
}
Reference :Quartz Task scheduling (1) Quick start to concept analysis
About Cron expression
Cron expression From left to right The meaning of each symbol is :
second、branch、when、Japan、month、Zhou、year

Reference material :
SpringBoot Timing task cron
On-line cron Expression generation
Why would you consider xxljob
Springboot Already defined in @Scheduled The function of timing task , At the same time, it can also support most of the business development requirements , But why still consider using xxl-job technology ?
In fact, in the official documents , It has a good description .
xxljob Server deployment
1、 download xxljob Source code
git clone https://github.com/xuxueli/xxl-job.git
2、 Import idea

3、 Initialize database

Execute it in your own database , This use is MySQL.
complete SQL The script is shown below :
#
# XXL-JOB v2.3.1-SNAPSHOT
# Copyright (c) 2015-present, xuxueli.
CREATE database if NOT EXISTS `xxl_job` default character set utf8mb4 collate utf8mb4_unicode_ci;
use `xxl_job`;
SET NAMES utf8mb4;
CREATE TABLE `xxl_job_info` (
`id` int(11) NOT NULL AUTO_INCREMENT,
`job_group` int(11) NOT NULL COMMENT ' Actuator primary key ID',
`job_desc` varchar(255) NOT NULL,
`add_time` datetime DEFAULT NULL,
`update_time` datetime DEFAULT NULL,
`author` varchar(64) DEFAULT NULL COMMENT ' author ',
`alarm_email` varchar(255) DEFAULT NULL COMMENT ' Alarm mail ',
`schedule_type` varchar(50) NOT NULL DEFAULT 'NONE' COMMENT ' Scheduling type ',
`schedule_conf` varchar(128) DEFAULT NULL COMMENT ' Scheduling configuration , The meaning of the value depends on the scheduling type ',
`misfire_strategy` varchar(50) NOT NULL DEFAULT 'DO_NOTHING' COMMENT ' Schedule expiration policy ',
`executor_route_strategy` varchar(50) DEFAULT NULL COMMENT ' Actuator routing strategy ',
`executor_handler` varchar(255) DEFAULT NULL COMMENT ' Actuator task handler',
`executor_param` varchar(512) DEFAULT NULL COMMENT ' Actuator task parameters ',
`executor_block_strategy` varchar(50) DEFAULT NULL COMMENT ' Blocking strategy ',
`executor_timeout` int(11) NOT NULL DEFAULT '0' COMMENT ' Task execution timeout , Unit second ',
`executor_fail_retry_count` int(11) NOT NULL DEFAULT '0' COMMENT ' Failed retries ',
`glue_type` varchar(50) NOT NULL COMMENT 'GLUE type ',
`glue_source` mediumtext COMMENT 'GLUE Source code ',
`glue_remark` varchar(128) DEFAULT NULL COMMENT 'GLUE remarks ',
`glue_updatetime` datetime DEFAULT NULL COMMENT 'GLUE Update time ',
`child_jobid` varchar(255) DEFAULT NULL COMMENT ' The subtasks ID, Multiple commas separate ',
`trigger_status` tinyint(4) NOT NULL DEFAULT '0' COMMENT ' Scheduling status :0- stop it ,1- function ',
`trigger_last_time` bigint(13) NOT NULL DEFAULT '0' COMMENT ' Last scheduling time ',
`trigger_next_time` bigint(13) NOT NULL DEFAULT '0' COMMENT ' Next scheduling time ',
PRIMARY KEY (`id`)
) ENGINE=InnoDB DEFAULT CHARSET=utf8mb4;
CREATE TABLE `xxl_job_log` (
`id` bigint(20) NOT NULL AUTO_INCREMENT,
`job_group` int(11) NOT NULL COMMENT ' Actuator primary key ID',
`job_id` int(11) NOT NULL COMMENT ' Mission , Primary key ID',
`executor_address` varchar(255) DEFAULT NULL COMMENT ' Actuator address , The address of this execution ',
`executor_handler` varchar(255) DEFAULT NULL COMMENT ' Actuator task handler',
`executor_param` varchar(512) DEFAULT NULL COMMENT ' Actuator task parameters ',
`executor_sharding_param` varchar(20) DEFAULT NULL COMMENT ' Actuator task fragmentation parameters , The format is as follows 1/2',
`executor_fail_retry_count` int(11) NOT NULL DEFAULT '0' COMMENT ' Failed retries ',
`trigger_time` datetime DEFAULT NULL COMMENT ' Dispatch - Time ',
`trigger_code` int(11) NOT NULL COMMENT ' Dispatch - result ',
`trigger_msg` text COMMENT ' Dispatch - journal ',
`handle_time` datetime DEFAULT NULL COMMENT ' perform - Time ',
`handle_code` int(11) NOT NULL COMMENT ' perform - state ',
`handle_msg` text COMMENT ' perform - journal ',
`alarm_status` tinyint(4) NOT NULL DEFAULT '0' COMMENT ' Alarm status :0- Default 、1- No alarm required 、2- Alarm successful 、3- Alarm failed ',
PRIMARY KEY (`id`),
KEY `I_trigger_time` (`trigger_time`),
KEY `I_handle_code` (`handle_code`)
) ENGINE=InnoDB DEFAULT CHARSET=utf8mb4;
CREATE TABLE `xxl_job_log_report` (
`id` int(11) NOT NULL AUTO_INCREMENT,
`trigger_day` datetime DEFAULT NULL COMMENT ' Dispatch - Time ',
`running_count` int(11) NOT NULL DEFAULT '0' COMMENT ' Running - Number of logs ',
`suc_count` int(11) NOT NULL DEFAULT '0' COMMENT ' Successful implementation - Number of logs ',
`fail_count` int(11) NOT NULL DEFAULT '0' COMMENT ' Execution failure - Number of logs ',
`update_time` datetime DEFAULT NULL,
PRIMARY KEY (`id`),
UNIQUE KEY `i_trigger_day` (`trigger_day`) USING BTREE
) ENGINE=InnoDB DEFAULT CHARSET=utf8mb4;
CREATE TABLE `xxl_job_logglue` (
`id` int(11) NOT NULL AUTO_INCREMENT,
`job_id` int(11) NOT NULL COMMENT ' Mission , Primary key ID',
`glue_type` varchar(50) DEFAULT NULL COMMENT 'GLUE type ',
`glue_source` mediumtext COMMENT 'GLUE Source code ',
`glue_remark` varchar(128) NOT NULL COMMENT 'GLUE remarks ',
`add_time` datetime DEFAULT NULL,
`update_time` datetime DEFAULT NULL,
PRIMARY KEY (`id`)
) ENGINE=InnoDB DEFAULT CHARSET=utf8mb4;
CREATE TABLE `xxl_job_registry` (
`id` int(11) NOT NULL AUTO_INCREMENT,
`registry_group` varchar(50) NOT NULL,
`registry_key` varchar(255) NOT NULL,
`registry_value` varchar(255) NOT NULL,
`update_time` datetime DEFAULT NULL,
PRIMARY KEY (`id`),
KEY `i_g_k_v` (`registry_group`,`registry_key`,`registry_value`)
) ENGINE=InnoDB DEFAULT CHARSET=utf8mb4;
CREATE TABLE `xxl_job_group` (
`id` int(11) NOT NULL AUTO_INCREMENT,
`app_name` varchar(64) NOT NULL COMMENT ' actuator AppName',
`title` varchar(12) NOT NULL COMMENT ' Actuator name ',
`address_type` tinyint(4) NOT NULL DEFAULT '0' COMMENT ' Actuator address type :0= Automatic registration 、1= Manually enter ',
`address_list` text COMMENT ' Actuator address list , Multiple addresses separated by commas ',
`update_time` datetime DEFAULT NULL,
PRIMARY KEY (`id`)
) ENGINE=InnoDB DEFAULT CHARSET=utf8mb4;
CREATE TABLE `xxl_job_user` (
`id` int(11) NOT NULL AUTO_INCREMENT,
`username` varchar(50) NOT NULL COMMENT ' account number ',
`password` varchar(50) NOT NULL COMMENT ' password ',
`role` tinyint(4) NOT NULL COMMENT ' role :0- Ordinary users 、1- Administrators ',
`permission` varchar(255) DEFAULT NULL COMMENT ' jurisdiction : actuator ID list , Multiple commas split ',
PRIMARY KEY (`id`),
UNIQUE KEY `i_username` (`username`) USING BTREE
) ENGINE=InnoDB DEFAULT CHARSET=utf8mb4;
CREATE TABLE `xxl_job_lock` (
`lock_name` varchar(50) NOT NULL COMMENT ' Lock name ',
PRIMARY KEY (`lock_name`)
) ENGINE=InnoDB DEFAULT CHARSET=utf8mb4;
INSERT INTO `xxl_job_group`(`id`, `app_name`, `title`, `address_type`, `address_list`, `update_time`) VALUES (1, 'xxl-job-executor-sample', ' Example actuators ', 0, NULL, '2018-11-03 22:21:31' );
INSERT INTO `xxl_job_info`(`id`, `job_group`, `job_desc`, `add_time`, `update_time`, `author`, `alarm_email`, `schedule_type`, `schedule_conf`, `misfire_strategy`, `executor_route_strategy`, `executor_handler`, `executor_param`, `executor_block_strategy`, `executor_timeout`, `executor_fail_retry_count`, `glue_type`, `glue_source`, `glue_remark`, `glue_updatetime`, `child_jobid`) VALUES (1, 1, ' Test task 1', '2018-11-03 22:21:31', '2018-11-03 22:21:31', 'XXL', '', 'CRON', '0 0 0 * * ? *', 'DO_NOTHING', 'FIRST', 'demoJobHandler', '', 'SERIAL_EXECUTION', 0, 0, 'BEAN', '', 'GLUE Code initialization ', '2018-11-03 22:21:31', '');
INSERT INTO `xxl_job_user`(`id`, `username`, `password`, `role`, `permission`) VALUES (1, 'admin', 'e10adc3949ba59abbe56e057f20f883e', 1, NULL);
INSERT INTO `xxl_job_lock` ( `lock_name`) VALUES ( 'schedule_lock');
commit;
4、 Modify the downloaded xxljob Source configuration file
such as :mysql Connection configuration :
spring.datasource.url=jdbc:mysql://106.55.137.66:3306/xxl_job?useSSL=false&useUnicode=true&characterEncoding=UTF-8&autoReconnect=true&serverTimezone=GMT%2B8
spring.datasource.username=root
spring.datasource.password=root
spring.datasource.driver-class-name=com.mysql.cj.jdbc.Driver
Then start directly xxl-job-admin This springboot It can be applied !
5、web visit
http://localhost:8080/xxl-job-admin/
Default account 、 The password for :
admin
123456
xxl-job Client Deployment
1、web End new actuator

2、 Configure test service
find xxl-job-executor-sample-springboot service , modify application.properties Configuration information .
# Application port number
server.port=80
# no web
#spring.main.web-environment=false
# log config
logging.config=classpath:logback.xml
# xxl-job web End address Be careful not to use... For address information 127.0.0.1
### xxl-job admin address list, such as "http://address" or "http://address01,http://address02"
xxl.job.admin.addresses=http://192.168.1.7:8080/xxl-job-admin
### xxl-job, access token
xxl.job.accessToken=
# xxl-job web Information configured in , Be consistent with it
### xxl-job executor appname
xxl.job.executor.appname=xj-job-test
### 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=192.168.1.7
xxl.job.executor.port=9998
### xxl-job executor log-path
xxl.job.executor.logpath=/data/applogs/xxl-job/jobhandler
### xxl-job executor log-retention-days
xxl.job.executor.logretentiondays=30

3、 Set up custom handler actuator
package com.xxl.job.executor.service.jobhandler;
import com.xxl.job.core.handler.annotation.XxlJob;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.stereotype.Component;
@Component
public class XJTestJobHandler {
private static Logger logger = LoggerFactory.getLogger(XJTestJobHandler.class);
// Notice the bean name
@XxlJob("testXJTestJobHandler")
public void test(){
logger.info("666666");
}
}
4、web Add task management configuration at the end

5、 start-up xxl-job-executor-sample-springboot
When the above parameters are configured ,xxl-job-executor-sample-springboot Not activated , here xxl-job-admin An error message will appear on the console .
because
xxl-job-adminWill try to execute once first , And then distributed to the sub service execution !
start-up xxl-job-executor-sample-springboot service .
After successful startup , stay xxl-job-executor-sample-springboot The following log information can be seen in the service console :
matters needing attention
1、xxl-rpc remoting error(no protocol: 127.0.0.1:8083/run), for url :
Note in the configuration file , Native test Do not use 127.0.0.1!
边栏推荐
- JS wechat games - fighting mosquitoes
- Installation and configuration of NPM and yarn
- Find target value
- Hevc HM learning 02
- 聊一聊蚂蚁AI技术里的“老实担当”
- Apispace sunrise sunset API interface is free and easy to use
- photoClip. JS mobile image upload and interception plug-in
- Interview question 08.01 Three step problem
- 蚂蚁集团三项技术方案入选“2021年信息技术应用创新典型解决方案”
- Tips for speeding up kettle insertion
猜你喜欢

【UE4自动地形材质】

High jump wechat JS game source code

Some beautiful JS prompt boxes

【通用数据库工具】上海道宁为开发者、分析师、数据库管理员带来适用于所有数据库和操作系统的工具——DbVisualizer

【无标题】

Yuandao communication has passed the registration: its annual revenue is 1.625 billion yuan, and its performance is highly dependent on China Mobile

Cubase pro 12

每日一题—LeetCode497—非重叠矩形中的随机点-前缀和-二分

2022制冷与空调设备运行操作特种作业证考试题库模拟考试平台操作

Odometer. JS digital scrolling plug-in
随机推荐
The meaning of likelihood function
[simplify] [exclude]
How to ensure system stability and achieve emission reduction? Ant group has these key technologies
2022危险化学品经营单位主要负责人考试试题及在线模拟考试
【UE4自动地形材质】
最高奖项!2022数博会领先科技成果“新技术”授予OceanBase数据库
Pytorch: sub model parameter freezing + BN freezing
2022.6.7-----leetcode. eight hundred and seventy-five
【通用数据库工具】上海道宁为开发者、分析师、数据库管理员带来适用于所有数据库和操作系统的工具——DbVisualizer
Hevc HM learning 02
Daily question - leetcode497 - random points in non overlapping rectangle - prefix and - bisection
2022 Shandong Province safety officer C certificate examination question bank and answers
.NET C#基础(7):接口 - 人如何和猫互动
Wechat mobile JS small game stepping on the box source code
How to use API interface of national weather forecast for rapid development
Array, string, function and structure in C language
文献阅读---玉米干旱响应和耐受性基因表达的调控变异定位
Add of pytorch_ How can module (name, module) be represented by mindspore
Top prize! The leading scientific and technological achievement "new technology" of 2022 digital Expo was awarded to oceanbase database
Custom tooltips prompt bubble JS plug-in