Quartz expression generation address: http://cron.qqe2.com
Support the generation of timed task expressions and inverse parsing. The timed tasks using Quartz expressions are as follows:
- xxl-job
- @ Scheduled for springboot
- Quartz framework
1, Five ways to create scheduled tasks
1. Create job scheduled tasks using threads
/** * TODO Create job scheduled tasks using threads * @author Wang */ public class JobThread { public static class Demo01 { static long count = 0; public static void main(String[] args) { Runnable runnable = new Runnable() { @Override public void run() { while (true) { try { Thread.sleep(1000); count++; System.out.println(count); } catch (Exception e) { // TODO: handle exception } } } }; Thread thread = new Thread(runnable); thread.start(); } } }
2. Create a job scheduled task using TimerTask
/** * TODO Create a job scheduled task using TimerTask * @author Wang */ public class JobTimerTask { static long count = 0; public static void main(String[] args) { TimerTask timerTask = new TimerTask() { @Override public void run() { count++; System.out.println(count); } }; //Create timer object and set interval time Timer timer = new Timer(); // Interval days long delay = 0; // Interval milliseconds long period = 1000; timer.scheduleAtFixedRate(timerTask, delay, period); } }
3. Create a job scheduled task using a thread pool
/** * TODO Create a job scheduled task using a thread pool * @author Wang */ public class JobScheduledExecutorService { public static void main(String[] args) { Runnable runnable = new Runnable() { @Override public void run() { // task to run goes here System.out.println("Hello !!"); } }; ScheduledExecutorService service = Executors.newSingleThreadScheduledExecutor(); // The second parameter is the delay time of the first execution, and the third parameter is the interval time of timed execution service.scheduleAtFixedRate(runnable, 1, 1, TimeUnit.SECONDS); } }
4. Quartz * * framework**
1. Introducing maven dependency
<dependencies> <!-- quartz --> <dependency> <groupId>org.quartz-scheduler</groupId> <artifactId>quartz</artifactId> <version>2.2.1</version> </dependency> <dependency> <groupId>org.quartz-scheduler</groupId> <artifactId>quartz-jobs</artifactId> <version>2.2.1</version> </dependency> </dependencies>
2. Task scheduling class
public class MyJob implements Job { @Override public void execute(JobExecutionContext context) throws JobExecutionException { System.out.println("quartz MyJob date:" + System.currentTimeMillis()); } }
3. Startup class
public class JobQuartz { public static void main(String[] args) throws SchedulerException { //1. Create the Scheduler's factory SchedulerFactory sf = new StdSchedulerFactory(); //2. Obtain the scheduler instance from the factory Scheduler scheduler = sf.getScheduler(); //3. Create JobDetail, JobDetail jb = JobBuilder.newJob(MyJob.class) //job description .withDescription("this is a ram job") //name and group of job .withIdentity("ramJob", "ramGroup") .build(); //The running time of the task. The SimpleSchedle trigger is valid. Start the task after 3 seconds long time= System.currentTimeMillis() + 3*1000L; Date statTime = new Date(time); //4. Create Trigger //Use SimpleScheduleBuilder or CronScheduleBuilder Trigger t = TriggerBuilder.newTrigger() .withDescription("") .withIdentity("ramTrigger", "ramTriggerGroup") //.withSchedule(SimpleScheduleBuilder.simpleSchedule()) //Start at current time by default .startAt(statTime) //Execute once every two seconds. Quartz expression supports all kinds of awesome expressions .withSchedule(CronScheduleBuilder.cronSchedule("0/2 * * * * ?")) .build(); //5. Register tasks and timers scheduler.scheduleJob(jb, t); //6. Start the scheduler scheduler.start(); }
5. springboot @ Scheduled annotation
@Component @Configuration //1. It is mainly used to mark configuration classes and has the effect of Component. @EnableScheduling // 2. Start scheduled tasks public class SaticScheduleTask { @Scheduled(cron = "0/5 * * * * ?") //3. Add Scheduled Task //@Scheduled(fixedRate=5000) / / or directly specify the time interval, for example: 5 seconds private void configureTasks() { System.err.println("Execution time of static scheduled task: " + LocalDateTime.now()); } }
2, XXL job task scheduling background Admin
What's the use of XXL job?
- In the case of distributed clusters, it is ensured that scheduled tasks are not repeated.
- The execution principle is the same as that of Nginx. All scheduled tasks are distributed through the task scheduling platform, and load balancing can also be configured
- First, let's use it and build our own task
The basic Spring Boot tutorial will not be introduced. It is recommended to see here: https://github.com/javastacks/spring-boot-best-practice
Step 1: github download source code import
Download address: https://github.com/xuxueli/xxl-job/
Current version directory structure 2.1.1
Step 2: execute sql
File address: XXL job / Doc / db / tables_ xxl_ job. sql
Current version 2.1.1 sql
Step 3: modify the XXL job admin project configuration
Configuration file: application properties
Modify database connection
Step 4: start the admin project
Start the project in springboot mode
visit http://localhost:8080/xxl-job-admin/
Account password: admin / 123456
The task scheduling center is set up
Next, you need to create a server to connect to the task scheduling center
3, Task XXL job of self created boot project
Create a boot project
My directory structure
pom.xml
web core and XXL job core
<!-- spring-boot-starter-web (spring-webmvc + tomcat) --> <dependency> <groupId>org.springframework.boot</groupId> <artifactId>spring-boot-starter-web</artifactId> </dependency> <dependency> <groupId>org.springframework.boot</groupId> <artifactId>spring-boot-starter-test</artifactId> <scope>test</scope> </dependency> <!-- xxl-job-core The version number is modified according to the version you downloaded --> <dependency> <groupId>com.xuxueli</groupId> <artifactId>xxl-job-core</artifactId> <version>2.1.1-SNAPSHOT</version> </dependency>
logback.xml
Log configuration direct copy
<?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-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>
application.properties add configuration
Need to modify or customize
- XXL job admin address
- xxl.job.executor.appname is a user-defined name, which must correspond to the background configuration
- xxl.job.executor.ip the current computer Ip, or the computer Ip of the deployment project
- xxl.job.executor.port port
# Port number server.port=8081 # journal logging.config=classpath:logback.xml ## XXL job admin address, separated by multiple commas“ xxl.job.admin.addresses=http://127.0.0.1:8080/xxl-job-admin ## XXL job name ðž“œ socket ip IP address of current project deployment / local ip | socket port number xxl.job.executor.appname=xxl-job-executor-sample xxl.job.executor.ip=192.168.43.153 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=-1
Add boot configuration class XxlJobConfig
/** * xxl-job xxljob.config */ @SuppressWarnings("ALL") @Configuration public class XxlJobConfig { private 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); System.err.println(ip+":"+port); return xxlJobSpringExecutor; } /** * For multiple network cards and internal deployment of containers, the registered IP can be flexibly customized with the help of the "InetUtils" component provided by "spring cloud commons"; * * 1,Import dependency: * <dependency> * <groupId>org.springframework.cloud</groupId> * <artifactId>spring-cloud-commons</artifactId> * <version>${version}</version> * </dependency> * * 2,Configuration file, or container startup variable * spring.cloud.inetutils.preferred-networks: 'xxx.xxx.xxx.' * * 3,Get IP * String ip_ = inetUtils.findFirstNonLoopbackHostInfo().getIpAddress(); */ }
Task job
@JobHandler(value="demoJobHandler") @Component public class DemoJobHandler extends IJobHandler { static int count; @Override public ReturnT<String> execute(String param) throws Exception { System.out.println("implement job task"+count++); return SUCCESS; } }
admin background configuration
Under execution manager
Edit task under task management
Timing rule generation: http://cron.qqe2.com/
job task name: @ JobHandler annotation value > > for example: @ JobHandler(value = "demoJobHandler")
start-up
This completes the configuration
Original link: https://blog.csdn.net/qq_41463655/article/details/100839629
Copyright notice: This article is the original article of CSDN blogger "Xi Jia Xiaoer", which follows the CC 4.0 BY-SA copyright agreement. For reprint, please attach the source link of the original text and this notice.
Recent hot article recommendations:
1.1000 + Java interview questions and answers (2021 latest version)
2.Finally got the IntelliJ IDEA activation code through the open source project. It's really fragrant!
3.Ali Mock tools are officially open source and kill all Mock tools on the market!
4.Spring Cloud 2020.0.0 is officially released, a new and subversive version!
5.Java development manual (Songshan version) is the latest release. Download it quickly!
Feel good, don't forget to like + forward!