SpringBoot four regular tasks

Regular tasks implemented in several ways:

The Timer : This is the java comes java.util.Timer class that allows you to schedule a task java.util.TimerTask.

This way allows you to program execution in accordance with a certain frequency, but can not run at the specified time. Usually less used.

The ScheduledExecutorService : jdk also comes with a class; timed task class is designed based on the thread pool

Each scheduled task is assigned to a thread pool thread to perform, that is to say, the task is complicated by the implementation of each other.

Task the Spring : After Spring3.0 own task, it can be viewed as a lightweight Quartz, but much simpler to use than Quartz.

The Quartz : This function is a more powerful scheduler that allows you to program execution at a specified time, can also be performed in a certain frequency, up slightly more complex configuration.

Use Timer

This is currently less used in the project, directly attached to the demo code. You can view specific introduction api

{class TestTimer public

   public static void main (String [] args) {

       the TimerTask the TimerTask the timerTask new new = () {
           @Override
           public void RUN () {
               System.out.println ( "Task RUN:" + new new a Date ());
           }

       };

       the Timer Timer new new = the Timer ();
        // specified task schedule specified fixed time delay for repeated execution. This is performed once every 3 seconds
        timer.schedule (the timerTask, 10,3000);
   }

}

使用ScheduledExecutorService

This method is similar with Timer, looking directly at the demo:

{class TestScheduledExecutorService public

   public static void main (String [] args) {

       The ScheduledExecutorService Executors.newSingleThreadScheduledExecutor-Service = ();
       // parameters: 1, the delay time of the task 2, first execution
       // 3, 4 task execution interval, the interval time units
       service.scheduleAtFixedRate (() -> System.out.println ( "Task The ScheduledExecutorService" + new new a Date ()), 0,. 3, TimeUnit.SECONDS);
   }

}

Use Spring Task

Simple timing task

In SpringBoot project, we can be very elegant use annotations to achieve timing task, first create a project, import dependence:

<dependencies>

 <dependency>
   <groupId>org.springframework.bootgroupId>
   <artifactId>spring-boot-starter-webartifactId>
 <dependency>

 <dependency>
   <groupId>org.springframework.bootgroupId>
   <artifactId>spring-boot-starterartifactId>
 <dependency>

 <dependency>
   <groupId>org.projectlombokgroupId>
   <artifactId>lombokartifactId>
   <optional>trueoptional>
 <dependency>

 <dependency>
   <groupId>org.springframework.bootgroupId>
   <artifactId>spring-boot-starter-testartifactId>
   <scope>testscope>
 <dependency>

<dependencies>

 

 

Create a task categories:

@Slf4j
@Component
public class ScheduledService {

   @Scheduled(cron = "0/5 * * * * *")
   public void scheduled(){
       log.info("=====>>>>>使用cron  {}",System.currentTimeMillis());
   }
   
   @Scheduled(fixedRate = 5000)
   public void scheduled1() {
       log.info("=====>>>>>使用fixedRate{}", System.currentTimeMillis());
   }

   @Scheduled(fixedDelay = 5000)
   public void scheduled2() {
       log.info("=====>>>>>fixedDelay{}",System.currentTimeMillis());
   }

}

Use @EnableScheduling comment on the main class of open support for regular tasks, and then start the project

We can see three timed tasks have been performed, and the same thread serial execution

If only one timed task, this is certainly no problem, when an increase in regular tasks, if a task stuck, lead to other tasks can not be performed.

Multi-threaded execution

In the traditional Spring project, we can add a task configuration in the xml configuration file, and add in SpringBoot project in general use config configuration configuration class, so a new class AsyncConfig

@Configuration
@EnableAsync
public class AsyncConfig {

    /*
     *此处成员变量应该使用@Value从配置中读取
    */
   private int corePoolSize = 10;
   private int maxPoolSize = 200;
   private int queueCapacity = 10;

   @Bean
   public Executor taskExecutor() {
       ThreadPoolTaskExecutor executor = new ThreadPoolTaskExecutor();
       executor.setCorePoolSize(corePoolSize);
       executor.setMaxPoolSize(maxPoolSize);
       executor.setQueueCapacity(queueCapacity);
       executor.initialize();
       return executor;
   }
}

@Configuration: Indicates that the class is a configuration class
@EnableAsync: open support for asynchronous events

@Async then added on a class or method timed tasks. Finally restart the project, each task is in a different thread.

Execution time configuration

In the timing of the above task, we used @Scheduled annotation on the task execution time setting method, and the configuration using three attributes:

fixedRate : definition of a scheduled task is executed according to a certain frequency

FIXEDDELAY : regular tasks executing in a defined frequency, different from the above, the attributes can be changed with the initialDelay, define the task execution time delay.

cron : to configure the task execution time by the expression

Detailed cron expression

A cron expression of at least 6 (and possibly 7) has time elements separated by spaces. By order:

Sec (0 to 59)

Min (0 - 59)

H (0 to 23)

Day (0 to 31)

Month (0 to 11)

Week (1 ~ 7 1 = SUN or SUN, MON, TUE, WED, THU, FRI, SAT)

Year (1970-2099)

Wherein each element can be a value (e.g., 6), a continuous section (9-12), a time interval (8-18 / 4) (/ indicates every 4 hours), a list (1,3,5) The wildcard.

As the "day of the month" and "date of the week," these two elements are mutually exclusive, and must be for one of the settings

Instance:

Executed once every 5 seconds: / 5 *?

Executed once every minute: 0/1?

00 10,14,16? 10 am every day, 14:00, 4:00

0 0/30 9-17? Inward nine to five hours every half hour

0 0 12? * WED represent every Wednesday 12:00

"0012?" 12:00 every day trigger

"01510?" Trigger every day at 10:15 am

"01510?" Trigger every day at 10:15 am

"01510? *" Trigger every day at 10:15 am

"01510? 2005" in 2005 triggered daily at 10:15 am

Every 1 minute when the "014 *?" During a day at 2:00 pm to 2:59 pm

"0 0/5 14?" Trigger every 5 minutes during the day at 2:00 pm to 2:55 pm

"0 0/5 14, 18?" During the 2:00 to 2:55 every afternoon and trigger every 5 minutes 6:00 pm to 6:55 during

"00-514? 'Trigger per minute during the day at 2:00 pm to 2:05 pm

"0 10,44 14? ​​3 WED" March of the year Wednesday afternoon 2:10 and 2:44 trigger

"0 15 10? * MON-FRI" Monday to Friday 10:15 am to trigger

"0151015 *?" Trigger 15th of each month at 10:15 am

"0 15 10 L *?" On the last day of each month at 10:15 am triggering

"0 15 10? * 6L" the last Friday of each month at 10:15 am triggering

"0 15 10? * 6L 2002-2005" 2002 years to 2005, the last Friday of each month at 10:15 am triggering

"01510? * 6 # 3" is the third Friday of each month at 10:15 am triggering

Some sub-expressions can contain a range or list

For example: subexpression (days (weeks)) can be "MON-FRI", "MON, WED, FRI", "MON-WED, SAT"

"*" Character represents all possible values
"/" character is used to specify the value of the increment

For example: In the subexpression (minutes) in the "0/15" starts from 0 minutes, every 15 minutes
in the sub-expression (minutes) in the "3/20" indicates the start of the 3 minutes, every 20 minutes (it "3,23,43") as meaning

"?" Character is used only day (month) and day (week) two sub-expression that do not specify a value
when one of the two sub-expressions which are assigned a value in the future, in order to avoid conflict, you need to express another child style value is set to "?"

"L" character is used only two sub-day (month) and day (week) expression, which is an abbreviation of the word "last" is
if there are specific content in the "L" before, it has other meanings of.

For example: "6L" represents the inverse of this month on day 6
Note: When using the "L" parameter, do not specify the list or range, as this can cause problems

W character represents the weekday (Mon-Fri), and can only be used for field day. It is used to specify the closest to a given day on weekdays.

Most business processes are based on the work week, so W character may be very important.

For example, Japanese domain 15W means "a number of the nearest month 15 weekdays." If the 15th is a Saturday, the trigger will trigger number (Friday) 14, because more recent than Monday from Thursday 15th.

C: represents the "Calendar" means. It means the date of the associated program, if the date is not associated with, the calendar equivalent of all dates.

For example 5C in the date field is equivalent to the first calendar day after the 5th. 1C corresponds to the field of the week Sunday after the first day.

 

Quartz integration

Add dependent

If SpringBoot later version is 2.0.0, then the spring-boot-starter has been included in reliance quart, you can directly use the spring-boot-starter-quartz-dependent:

<dependency>
    <groupId>org.springframework.bootgroupId>
    <artifactId>spring-boot-starter-quartzartifactId>
<dependency>

If you are dependent on 1.5.9 will have to add the following:

<dependency>
  <groupId>org.quartz-schedulergroupId>
  <artifactId>quartzartifactId>
  <version>2.3.0version>
<dependency>

<dependency>
  <groupId>org.springframeworkgroupId>
  <artifactId>spring-context-supportartifactId>
<dependency>

这里我使用SpringBoot版本是2.0.0.BUILD-SNAPSHOT ,该版本开始集成了Quartz,所以事实现起来很方便。

其它好像比较麻烦,这里就不介绍,以后有时间再详细深入了解Quartz。

创建任务类TestQuartz,该类主要是继承了QuartzJobBean

public class TestQuartz extends QuartzJobBean {

    /**
     * 执行定时任务
     * @param jobExecutionContext
     * @throws JobExecutionException
     */
    @Override
    protected void executeInternal(JobExecutionContext jobExecutionContext) throws JobExecutionException {
        System.out.println("quartz task "+new Date());
    }

}

创建配置类QuartzConfig

@Configuration
public class QuartzConfig {

    @Bean
    public JobDetail teatQuartzDetail(){
        return JobBuilder.newJob(TestQuartz.class).withIdentity("testQuartz").storeDurably().build();
    }

    @Bean
    public Trigger testQuartzTrigger(){
        SimpleScheduleBuilder scheduleBuilder = SimpleScheduleBuilder.simpleSchedule()
        
                .withIntervalInSeconds(10)  //设置时间周期单位秒
                .repeatForever();
                
        return TriggerBuilder.newTrigger().forJob(teatQuartzDetail())

                .withIdentity("testQuartz")
                .withSchedule(scheduleBuilder)
                .build();
    }
}

启动项目

上面都是简单的介绍了关于SpringBoot定时任务的处理,直接使用SpringTask注解的方式应该是最方便的,而使用Quartz从2.0开始也变得很方便。

对于这两种方式,应该说各有长处吧,按需选择。另外关于Quartz的详细内容可以查看官方文档

 

End

Guess you like

Origin www.cnblogs.com/HHR-SUN/p/11595805.html