SpringBoot seventeenth chapter: regular tasks

Author: Dream 1819
Original: https://blog.csdn.net/weixin_39759846/article/details/93481921
Copyright: This article is a blogger original article, reproduced, please attach Bowen link!

 

introduction

  I believe we are very familiar with the timing of the task, and its importance is self-evident. Timing send text messages, timed batch operations, timing statistics, etc., are inseparable from the regular tasks. This article will explain the timing of application tasks in SpringBoot project.

 

Version Information

  • JDK:1.8
  • SpringBoot :2.0.1.RELEASE
  • maven:3.3.9
  • IDEA:2019.1.1
  • quartz:2.3.0

 

The timing of implementation of tasks

JDK comes with Timer

  Timer is a Java class that comes with regular tasks. The timing can be used as a relatively simple task. Usually not much. Below is a small example to demonstrate its use.

 

SpringBoot integrated schedule

This approach is SpringBoot integrated, easy to use.

First, the foundation introduced SpringBoot jar:

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

 

And then start the class add annotations  @EnableScheduling to open SpringBoot regular tasks:

@SpringBootApplication
@EnableScheduling
public class TimedTaskDemoApplication {
    public static void main(String[] args) {
        SpringApplication.run(TimedTaskDemoApplication.class, args);
    }
}

 

Below according to  @Scheduled different attributes to create several tasks:

Task One:

@Component
public class FirstTask {
    /**
     * cron 表达式
     */
//    @Scheduled(cron = "0/2 * * * * *")
    @Scheduled(cron="${cron.schedule}")
    public void run(){
        System.out.println("这是创建的第一个定时任务");
    }
}

Some explanations for:

  1. cron expression is  @Scheduled one of the attribute, whose value can be set directly cron expression;
  2. @Scheduled(cron="${cron.schedule}") It is a dynamic expression application.properties read cron configuration file. For example, a project that needs daily 0:00 to perform, but for testers, can not wait until the morning test. Dynamic reading can help solve the problem.
     

Task Two:

@Component
public class SecondTask {
    /**
     * 上一次执行完毕时间点之后多长时间再执行(ms)
     */
    @Scheduled(fixedDelay = 2000)
    public void run(){
        System.out.println("这是创建的第二个定时任务");
    }
}

 

Task three:

@Component
public class ThirdTask {
    /**
     * 与fixedDelay功能相同,上一次执行完毕时间点之后多长时间再执行(ms),区别是:1、时间是字符串;2、支持占位符
     */
    // @Scheduled(fixedDelayString = "2000")
    @Scheduled(fixedDelayString = "${time.fixedDelay}")
    public void run(){
        System.out.println("这是创建的第三个定时任务");
    }
}

 

The three tasks listed above three parameters @Scheduled annotations. In fact, in addition to see @Scheduled source shows that there are a few remaining parameters:

  • fixedRate: after a point in time started on how long the re-execution;
  • fixedRateString: after a point in time started on how long the re-execution;
  • fixedRateString: with fixedRate the same meaning, except as a string. The only difference is that support a placeholder;
  • initialDelay: How long before the first delay execution;
  • initialDelayString: same meaning initialDelay, except for using a string. The only difference is that support a placeholder;

 

Quartz integration

  If the above methods are unable to meet the needs of the project, you can try the Quartz scheduling framework. It features a powerful and use without much to say. Here we take a look at the Quartz in SpringBoot.

Create a project, the introduction of Quartz scheduling framework starters:

<dependency>
    <groupId>org.springframework.boot</groupId>
    <artifactId>spring-boot-starter-quartz</artifactId>
</dependency>

 

  Note that the version information, if SpringBoot version after version 2.0, can be directly introduced Quartz starter. But if it is 2.0 the previous version, you need to introduce the following jar package:

<dependency>
    <groupId>org.quartz-scheduler</groupId>
    <artifactId>quartz</artifactId>
    <version>2.3.0</version>
</dependency>
<dependency>
    <groupId>org.springframework</groupId>
    <artifactId>spring-context-support</artifactId>
</dependency>

 

The following create tasks:

public class QuartzTask extends QuartzJobBean {
    @Override
    protected void executeInternal(JobExecutionContext jobExecutionContext) throws JobExecutionException {
        System.out.println(new Date());
    }
}

QuartzJobBean task needs to inherit the abstract class, and override executeInternal method.

 

The third step is to create a quartz configuration class, add  @Configuration annotations:

@Configuration
public class QuartzConfig {
    @Bean
    public JobDetail testQuartzTask() {
        return JobBuilder.newJob(QuartzTask.class).withIdentity("quartztask").storeDurably().build();
    }
    @Bean
    public Trigger testQuartzTrigger2() {
        //cron方式,每隔5秒执行一次
        return TriggerBuilder.newTrigger().forJob(testQuartzTask())
                .withIdentity("quartztask")
                .withSchedule(CronScheduleBuilder.cronSchedule("*/5 * * * * ?"))
                .build();
    }
}

  The above example is the use of cron expression, of course, may be a fixed time interval. This section describes the integration of Quartz and SpringBoot, no detail use of Quartz. Interested readers can log on Quartz's official website  or the Chinese official website of its own research.

 

to sum up

  There are regular implementation tasks are many ways in addition to the above mentioned, as well as regular tasks using the thread pool implementation, the system is to achieve some regular tasks Liunx. In short, the implementation of a variety of timed tasks in a manner that while the election according to the actual situation of the project. In order to achieve must not be achieved.



Guess you like

Origin blog.csdn.net/weixin_39759846/article/details/93481921