In addition to Weibo, there is also WeChat
Please pay attention
WeChat public account
Shulou
2025-01-18 Update From: SLTechnology News&Howtos shulou NAV: SLTechnology News&Howtos > Development >
Share
Shulou(Shulou.com)06/02 Report--
This article shows you what the timed task framework commonly used in java is, which is concise and easy to understand, which can definitely brighten your eyes. I hope you can get something through the detailed introduction of this article.
1. Timer+TimerTask
This is the java.util.Timer class that comes with jdk, which allows you to schedule a java.util.TimerTask task.
In this way, your program can be executed at a certain frequency, but not at a specified time, and it is generally used less.
/ * * @ Description: 1. Timer+TimerTask: (included with jdk) * this is the java.util.Timer class that comes with java, which allows you to schedule a java.util.TimerTask task. * in this way, your program can be executed at a certain frequency, but not at a specified time. It is generally used less. * @ Author: jianweil * @ date: 13:36 on 2021-12-14 * / public class TimerTest {public static void main (String [] args) {TimerTask timerTask = new TimerTask () {@ Override public void run () {System.out.println ("task run:" + new Date ());}} TimerTask timerTask2 = new TimerTask () {@ Override public void run () {System.out.println ("task2 run:" + new Date ()); / / when multithreading processes scheduled tasks in parallel, when Timer runs multiple TimeTask, as long as one of them does not catch the thrown exception, the other tasks will automatically stop running, which is not a problem with ScheduledExecutorService. Int I = 1Comp0;}}; / / idea will prompt: use ScheduledExecutorService instead of Timer Timer timer = new Timer (); System.out.println ("begin:" + new Date ()); / / schedule the specified task to be executed with a fixed delay of repetition at the specified time. Here is a delay of 5 seconds to start execution, followed by timer.schedule (timerTask, 5000, 3000) every 3 seconds; timer.schedule (timerTask2, 5000, 3000);}}
When multithreading processes scheduled tasks in parallel, when Timer runs multiple TimeTask, as long as one of them does not catch the thrown exception, the other tasks will automatically stop running, which is not a problem with ScheduledExecutorService.
II. ScheduledExecutorService
ScheduledExecutorService is also a timing class that comes with jdk, which can replace Timer.
Package com.ljw.springboottimer.scheduledExecutorservice;import org.apache.commons.lang3.concurrent.BasicThreadFactory;import java.util.Date;import java.util.concurrent.ScheduledExecutorService;import java.util.concurrent.ScheduledThreadPoolExecutor;import java.util.concurrent.TimeUnit / * * @ Description: 2. When ScheduledExecutorService replaces Timer (included with jdk) * when Timer runs multiple TimeTask, as long as one of them does not catch the thrown exception, the other tasks will automatically terminate. * there is no such problem when using ScheduledExecutorService. * @ Author: jianweil * @ date: 13:42 on 2021-12-14 * / public class ScheduledExecutorServiceTest {public static void main (String [] args) throws InterruptedException {/ / when all non-daemon threads end, the program terminates and kills all daemon threads in the process. Conversely, as long as any non-daemon thread is running, the program will not terminate. ScheduledExecutorService executorService = new ScheduledThreadPoolExecutor (1, new BasicThreadFactory.Builder () .namingPattern ("example-schedule-pool-%d") .daemon (false) .build (); System.out.println ("begin:" + new Date ()) / / parameters: 1, task body 2, delay time for the first execution 3, task execution interval 4, interval time unit / / delay 5 seconds Then executorService.scheduleAtFixedRate (new Runnable () {@ Override public void run () {/ / do something System.out.println ("begin:" + new Date ()) is executed every 3 seconds. }}, 5,3, TimeUnit.SECONDS);}} III, Spring Task
Classes provided by spring that introduce dependencies:
Org.springframework.boot spring-boot-starter
Start timing task: @ EnableScheduling
Use: add @ Scheduled to the corresponding task method
3.1 single-threaded serial execution-@ Scheduled
The @ Scheduled annotation makes serial execution in the same thread by default. If there is only one scheduled task, this will be fine. When the number of scheduled tasks increases, if one task is stuck, other tasks will not be executed.
Business testing:
@ Component@EnableSchedulingpublic class SpringTaskTest {@ Scheduled (cron = "0go 5 *") public void run () throws InterruptedException {System.out.println (Thread.currentThread (). GetName () + "= > using cron {}" + (System.currentTimeMillis () / 1000));} 3.2 Multithreading concurrent running-@ Scheduled+ configure timer pool (recommended)
To solve the problem of single-thread serial execution of tasks, it is necessary to configure the program pool of the timer. This method is recommended.
Just configure and inject a TaskScheduler class bean
The thread pool classes for configuring timers are as follows:
Package com.ljw.springboottimer.springtask;import org.springframework.context.annotation.Bean;import org.springframework.context.annotation.Configuration;import org.springframework.scheduling.TaskScheduler;import org.springframework.scheduling.concurrent.ThreadPoolTaskScheduler / * * @ Description: solve the thread pool of single-thread serial execution mode 2: jianweil scheduled + configuration timer * @ Author: jianweil * @ date: 14:44 on 2021-12-14 * / @ Configurationpublic class TaskSchedulerConfig {/ * initializes a TaskScheduler with a thread pool size of 5 Avoids all tasks using a single thread to execute * * @ return * / @ Bean public TaskScheduler taskScheduler () {ThreadPoolTaskScheduler taskScheduler = new ThreadPoolTaskScheduler () TaskScheduler.setPoolSize (5); taskScheduler.setThreadNamePrefix ("TaskSchedulerConfig-ljw"); return taskScheduler;}}
Business testing
@ Component@EnableSchedulingpublic class SpringTaskTest {@ Scheduled (cron = "0go 5 *") public void run () throws InterruptedException {System.out.println (Thread.currentThread () .getName () + "= > use cron {}" + (System.currentTimeMillis () / 1000)) } @ Scheduled (fixedRate = 5000) public void run1 () throws InterruptedException {System.out.println (Thread.currentThread (). GetName () + "= > using fixedRate {}" + (System.currentTimeMillis () / 1000));}} 3.3 concurrent execution of multiple threads-@ Scheduled+@Async+ configuration Asynchronous Thread Pool
To solve the problem of single-thread serial execution of tasks, it can also be implemented with asynchronous annotation @ Async, but this method is not recommended and requires two annotations.
It can also solve the situation that fixedRate encounters some tasks whose execution time exceeds the configured time interval, and the next task time comes and waits for the completion of the last task execution, which cannot be solved by 3.2.
Configure the asynchronous thread pool classes as follows:
Package com.ljw.springboottimer.springtask;import org.springframework.context.annotation.Configuration;import org.springframework.scheduling.annotation.AsyncConfigurer;import org.springframework.scheduling.annotation.EnableAsync;import org.springframework.scheduling.concurrent.ThreadPoolTaskExecutor;import java.util.concurrent.Executor;import java.util.concurrent.ThreadPoolExecutor / * * @ Description: solve the problem of single-threaded serial execution mode 1jianweil Async+ configure asynchronous thread pool * @ Author: jianweil * @ date: 2021-12-14 14:35 * / @ Configuration@EnableAsyncpublic class AsyncConfig implements AsyncConfigurer {/ * define @ Async default thread pool * ThreadPoolTaskExecutor is not completely managed by the IOC container bean, you can add @ Bean annotation to the method to be managed by the container This removes the taskExecutor.initialize () method call The container automatically calls * * @ return * / @ Override public Executor getAsyncExecutor () {int processors = Runtime.getRuntime () .availableProcessors () / / commonly used actuator ThreadPoolTaskExecutor taskExecutor = new ThreadPoolTaskExecutor (); / / number of core threads taskExecutor.setCorePoolSize (10); taskExecutor.setMaxPoolSize (50); / / maximum number of threads in the thread queue. Default: 50 taskExecutor.setQueueCapacity (100); / / thread name prefix taskExecutor.setThreadNamePrefix ("AsyncConfig-ljw-"); taskExecutor.setRejectedExecutionHandler (new ThreadPoolExecutor.CallerRunsPolicy ()) / / perform initialization (important) taskExecutor.initialize (); return taskExecutor;}}
Business testing requires @ Async annotations
@ Component@EnableSchedulingpublic class SpringTaskTest {@ Scheduled (cron = "0go 5 *") @ Async public void run () throws InterruptedException {System.out.println (Thread.currentThread () .getName () + "= > use cron {}" + (System.currentTimeMillis () / 1000)) } @ Scheduled (fixedRate = 5000) @ Async public void run1 () throws InterruptedException {System.out.println (Thread.currentThread () .getName () + "= > use fixedRate {}" + (System.currentTimeMillis () / 1000));}}
If both the 3.2configuration timer pool and 3.3configuration asynchronous thread pool are configured, and @ Scheduled+@Async is used in the annotation, the thread pool used by the timing task is: configure asynchronous thread pool
3. 4 @ Scheduled parameter resolution
Cron: configure task execution time through cron expressions (default is fixedDelay)
InitialDelay: defines how long the task will be delayed before it is executed for the first time
FixedRate: defines a scheduled task that is executed at a certain frequency. After the end of each task, fixedRate will find the next task to be executed from the task schedule to determine whether it is time to execute. No matter how long the fixedRate task is, it will not cause two task instances to be executed at the same time, and you have to wait until the last task is completed to determine whether the task is executed at the right time, regardless of the thread pool, unless the @ Async annotation is used to make the method asynchronous, that is, the 5.3step configuration is used. (5.2 is to configure the thread pool, which cannot achieve the effect)
FixedDelay: defines a scheduled task that is executed at a certain frequency. FixedDelay always delays a fixed length of time after the completion of the previous task, and then executes the next task
IV. Quartz
When developing Quartz-related applications, a timing scheduling capability can be realized as long as Job (task), JobDetail (task description), Trigger (trigger) and Scheduler (scheduler) are defined.
If the SpringBoot version is later than 2.0.0 and quart dependencies are already included in spring-boot-starter, you can introduce dependencies directly:
Org.springframework.boot spring-boot-starter-quartz4.1. Create a task class
Method 1: implement the execute method of the Job class to implement a task (recommended)
Task 1 is as follows:
Package com.ljw.springboottimer.quartz.do1;import org.quartz.Job;import org.quartz.JobExecutionContext;import org.quartz.JobExecutionException;import java.util.Date / * * @ Description: my scheduled task-method 1 * @ Author: jianweil * @ date: 16:06 * / public class MyTaskService1 implements Job {@ Override public void execute (JobExecutionContext jobExecutionContext) throws JobExecutionException {System.out.println (Thread.currentThread (). GetName () + "- Job -" + new Date ());}}
Method 2: inherit the QuartzJobBean class override method to implement a task
Task 2 is as follows:
Package com.ljw.springboottimer.quartz.do1;import org.quartz.JobExecutionContext;import org.quartz.JobExecutionException;import org.springframework.scheduling.quartz.QuartzJobBean;import java.util.Date / * * @ Description: my scheduled task-method 2 * @ Author: jianweil * @ date: 16:06 * / public class MyTaskService2 extends QuartzJobBean {@ Override protected void executeInternal (JobExecutionContext context) throws JobExecutionException {System.out.println (Thread.currentThread (). GetName () + "--QuartzJobBean-" + new Date ());} 4.2. Configure task descriptions and triggers
The configuration class declares two bean for each task.
1.JobDetail (Task description)
2.Trigger (trigger)
Configure scheduler information using SimpleScheduleBuilder or CronScheduleBuilder
Package com.ljw.springboottimer.quartz.do1;import org.quartz.*;import org.springframework.context.annotation.Bean;import org.springframework.context.annotation.Configuration;import java.util.Date;/** * @ Description: each task needs to be configured in two steps * 1. Configuration task description JobDetail 2. Configure trigger Trigger * @ Author: jianweil * @ date: 16:08 on 2021-12-14 * / @ Configurationpublic class QuartzConfig {/ * create task 1 JobDetail1 * * @ return * / @ Bean public JobDetail teatQuartzDetail1 () {return JobBuilder.newJob (MyTaskService1.class) / / job description .withDescription ("this is a job1") / / name and group .withIdentity of job ("myTrigger1" "myTriggerGroup1") .storeDuried () .build () } / * create task 2 JobDetail2 * * @ return * / @ Bean public JobDetail teatQuartzDetail2 () {return JobBuilder.newJob (MyTaskService2.class) / / job description .withDescription ("this is a job2") / / job name and group .identity ("myTrigger2") "myTriggerGroup2") .storeDuried () .build () } / * create Task 1 Trigger1 * * @ return * / @ Bean public Trigger testQuartzTrigger1 () {/ / use SimpleScheduleBuilder or CronScheduleBuilder SimpleScheduleBuilder scheduleBuilder = SimpleScheduleBuilder.simpleSchedule () / / set the time period in seconds. WithIntervalInSeconds (10) .repeatForever () / / execute once every two seconds, Quartz expression, which supports various powerful expressions CronScheduleBuilder cronScheduleBuilder = CronScheduleBuilder.cronSchedule ("0max 3 *?"); / / the time the task runs, the SimpleSchedle type trigger is valid, and the task starts after 3 seconds long time = System.currentTimeMillis () + 3 * 1000L; Date statTime = new Date (time) Return TriggerBuilder.newTrigger () .withDescription ("") .forJob (teatQuartzDetail1 ()) .withIdentity ("myTrigger1", "myTriggerGroup1") / / start .startAt (statTime) .withschedule (cronScheduleBuilder) / / .withschedule (scheduleBuilder) .build () } / * create Task 2 Trigger2 * * @ return * / @ Bean public Trigger testQuartzTrigger2 () {SimpleScheduleBuilder scheduleBuilder = SimpleScheduleBuilder.simpleSchedule () / / set the time period in seconds. Withinterval InSeconds (10) .repeatForever () Return TriggerBuilder.newTrigger () .forJob (teatQuartzDetail2 ()) .withIdentity ("myTrigger2", "myTriggerGroup2") .withSchedule (scheduleBuilder) .build ();}} the above is what the scheduled task framework is commonly used in java. Have you learned any knowledge or skills? If you want to learn more skills or enrich your knowledge reserve, you are welcome to follow the industry information channel.
Welcome to subscribe "Shulou Technology Information " to get latest news, interesting things and hot topics in the IT industry, and controls the hottest and latest Internet news, technology news and IT industry trends.
Views: 0
*The comments in the above article only represent the author's personal views and do not represent the views and positions of this website. If you have more insights, please feel free to contribute and share.
Continue with the installation of the previous hadoop.First, install zookooper1. Decompress zookoope
"Every 5-10 years, there's a rare product, a really special, very unusual product that's the most un
© 2024 shulou.com SLNews company. All rights reserved.