springBoot adds timer

Integrate Quartz

add dependencies

If the SpringBoot version is later than 2.0.0, the quart dependency is already included in the spring-boot-starter, and the spring-boot-starter-quartz dependency can be used directly:

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

If it is 1.5.9, use the following to add dependencies:

<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>

Here I use SpringBoot version 2.0.0.BUILD-SNAPSHOT, this version began to integrate Quartz, so it is very convenient to implement. Others seem to be more troublesome, so I won’t introduce them here, and I will learn about Quartz in detail later when I have time.

Create a task class TestQuartz, which mainly inherits 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());

    }

}

Create a configuration class 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();

    }

}

Startup project

The above is a brief introduction to the processing of SpringBoot timing tasks. It should be the most convenient way to directly use SpringTask annotations, and it has become very convenient to use Quartz since 2.0. For these two methods, it should be said that each has its own advantages, and you can choose according to your needs. In addition, for more details about Quartz, please refer to the official document

Original article: https://cloud.tencent.com/developer/article/1445905

Guess you like

Origin blog.csdn.net/shileimohan/article/details/128564028