Some people use Quartz, and some people may have built a set of scheduling platform. Springboot supports fixed tasks, making it easy to create scheduled tasks. Today, let’s talk about the creation of scheduled tasks in Springboot.
Creating a scheduled task in Springboot
There are two main ways to create a springboot scheduled task
- Create by annotations
- Through the interface provided in SpringBoot
Springboot creates scheduled tasks through annotations
First, introduce poM
Mainly used in class to @ EnableScheduling annotations, all in the org. Springframework: spring – the context under the package
Will introduce org. Springframework: spring – the context this package can be used
<dependency>
<groupId>org.springframework</groupId>
<artifactId>spring-context</artifactId>
<version>${spring.version}</version>
</dependency>
Copy the code
Go straight to the code and do a chestnut
import org.springframework.scheduling.annotation.EnableScheduling; import org.springframework.scheduling.annotation.Scheduled; import org.springframework.stereotype.Component; import java.text.SimpleDateFormat; import java.util.Date; /** * @createdTime: 2020/4/7 16:00. * @version: @component @enablesCheduling Public Class TestTask {private static ThreadLocal<SimpleDateFormat> dateFormat = ThreadLocal.withInitial(() -> new SimpleDateFormat("yyyy-MM-dd HH:mm:ss")); // Use @scheduled annotations on methods to create specific Scheduled tasks @scheduled (cron = "0/10 * * * *?" ) private void task1() {system.err.println (" + dateformat.get ().format(new Date())); }}Copy the code
Take a look at the execution result:
Class EnableScheduling (@component); class EnableScheduling (@component);
For specific methods that need to be executed Scheduled, use the @scheduled annotation. The annotations have a variety of arguments. I’m using cron expressions here
@scheduled annotations for each parameter
- cron
Scheduled(cron = “0/10 * * * *?”) String cron() default “”; Note: CRon expression, is our daily use of cron, specific will not post out
- zone
Scheduled(@scheduled) (zone = “GMT+08:00”) TimeZone, cron expression will be based on this TimeZone resolution, default empty, will take the application server’s TimeZone, generally do not fill in, and the JDK TimeZone is unified system, not specifically said
- fixedDelay
@scheduled (fixedDelay = 1) long fixedDelay() default-1; Description: How long has it been since the last execution, in milliseconds
- fixedDelayString
@scheduled (fixedDelayString = “1”) @scheduled (fixedDelayString = “${configuration file value}”) String fixedDelayString() default “”; Note: Like fixedDelay, it is a string value that can be filled in milliseconds. You can use the value in the configuration file in the same way as the Spring injection configuration file
- fixedRate
@scheduled (fixedRate = 1) long fixedRate() default-1; Note: How much time has passed since the last execution, in milliseconds
- fixedRateString
@scheduled (fixedRateString = “1”) @scheduled (fixedRateString = “${configuration file value}”) String fixedRateString() default “”; Like fixedRate,, is a string number that can be filled in milliseconds. You can use the value in the configuration file in the same way as the Spring injection configuration file is used
- initialDelay
@scheduled (initialDelay = 1) Long initialDelay() default-1; Note: How much time elapsed after the first execution of the command, in milliseconds
- initialDelayString
@scheduled (initialDelayString = “1”) @scheduled (initialDelayString = “${configuration file value}”) String initialDelayString() default “”; InitialDelay is the same as initialDelay, and is a string value in milliseconds. You can use the value in the configuration file in the same way as the Spring injection configuration file
Springboot creates scheduled tasks through the injection interface
Through the interface to create timing, will be more flexible, timing cron expression doesn’t have to write dead on the annotation of the code, can be stored in the database storage system, such as in the interface to obtain the expression of this configuration, so that we can realize a simple task scheduling platform, through the database configuration can manage timing task execution
Implement the interface SchedulingConfigurer
Main use is the interface SchedulingConfigurer, he is org. Springframework. Scheduling. The annotation. SchedulingConfigurer path this bag. Is all in the org. Springframework: spring – the context under the package
Will introduce org. Springframework: spring – the context this package can be used
<dependency>
<groupId>org.springframework</groupId>
<artifactId>spring-context</artifactId>
<version>${spring.version}</version>
</dependency>
Copy the code
The main method
Rewrite the configureTasks method via ScheduledTaskRegistrar to add the timing task. Roughly speaking, the input parameter is basically a thread object. The last parameter is the same as the cron expression in the annotation. How long after that, initial
Go straight to the code and do a chestnut
import org.springframework.scheduling.TaskScheduler; import org.springframework.scheduling.annotation.EnableScheduling; import org.springframework.scheduling.annotation.SchedulingConfigurer; import org.springframework.scheduling.config.ScheduledTaskRegistrar; import org.springframework.scheduling.config.Task; import org.springframework.stereotype.Component; import java.text.SimpleDateFormat; import java.util.Date; /** * @createdTime: 2020/4/7 18:33. * @version: */ @component @enablesCheduling public Class TestTask2 implements SchedulingConfigurer {private static ThreadLocal<SimpleDateFormat> dateFormat = ThreadLocal.withInitial(() -> new SimpleDateFormat("yyyy-MM-dd HH:mm:ss")); /** * Callback allowing a {@link TaskScheduler * TaskScheduler} and specific {@link Task Task} * instances to be registered against the given the {@link ScheduledTaskRegistrar}. * * @param taskRegistrar the registrar to be configured. */ @Override public void configureTasks(ScheduledTaskRegistrar taskRegistrar) { System.err.println(" Pretend to get the configured scheduled task execution plan from the database "); String cron = "0/10 * * * * ?" ; TaskRegistrar. AddCronTask (() - > {System. Err. Println (" interface timing task execution time task, the execution time is: "+ dateFormat. The get (). The format (new Date ())); },cron); }}Copy the code
The ScheduledTaskRegistrar object is used to create the scheduled task via overriding the configureTasks method. The expression can be read via the database via the ScheduledTaskRegistrar object and the implementation is simple:
Springboot to create a scheduled task for you to say here, welcome everyone to exchange, point out some of the article said wrong, let me deepen my understanding.
Thank you!