Spring Boot provides a very simple way to implement Scheduled tasks with the @scheduled annotation, which can be easily done with just two annotations.
1. Get started quickly@Scheduled
To use the @scheduled annotation in Spring Boot, start with the @enablesCheduling annotation on the Boot class
@Configuration
@EnableScheduling
public class ScheduleConfig {}@Component
public class ScheduleTask {
private static final Logger LOGGER = LoggerFactory.getLogger(ScheduleTask.class);
// Triggers once per second
@Scheduled(cron = "* * * * * ?" )
public void printLog(a) {
LOGGER.warn("Perform scheduled tasks"); }}Copy the code
In fact, all classes managed by Spring Boot can take effect. For example, the @Component@Configuration annotation can take effect only once. It is recommended to configure the annotation to the Boot class or a separate Configuration class to facilitate reading and locating problems.
Note:
- The task class needs to add annotations such as
@Component
To perform scheduled tasks, entrust the Bean to Spring management - If a class is
@Lazy
The modifier causes Spring Boot to start upWithout instantiation, the scheduled task will not start executing.
@Lazy
@Component
public class ScheduleTask {
private static final Logger LOGGER = LoggerFactory.getLogger(ScheduleTask.class);
// The scheduled task will not be executed
@Scheduled(cron = "* * * * * ?" )
public void printLog(a) {
LOGGER.warn("Perform scheduled tasks"); }}Copy the code
@Scheduled
annotations
fixedRate
: Call once every specified time, regardless of whether the task is completed.fixedDelay
: The call is invoked at a specified time after the task is executed.cron
: Executes as an expression, using toolsWeb siteTo quickly generate
The above three attributes can only choose one, see the org. Springframework. Scheduling. The annotation. Comments on the Scheduled class content
Annotation that marks a method to be scheduled. Exactly one of the @link #cron}, {@link #fixedDelay}, or {@link #fixedRate} attributes must be pecified.
So when the scheduled task of cron expression is not completed and the execution time is reached, it will not continue to execute. Please refer to
If you still need to execute, you can add the @async annotation and make the method asynchronous.
In general, cron expressions are not written to death. Cron is usually placed in the YML configuration file as a configuration for easy modification and maintenance
@Scheduled(cron = "${cron:* * * * * ? } ")
public void printLog(a) {
LOGGER.warn("Perform scheduled tasks");
}
Copy the code
# yML file. If not, the default * * * * *?
cron: 0/ 5 * * * * ?
Copy the code
To dynamically modify configuration files, you can use Apollo
2. Implementation of multi-thread timed task
Multi-threaded tasks in the Spring the Boot and the previous version 2.0 needs to implement SchedulingConfigurer interface, TaskSchedulingAutoConfiguration version 2.1 provides automatic configuration after class, You can add the required configuration to the YML file based on the TaskSchedulingProperties configuration items.
Implementation before 2.0
@Configuration
@EnableScheduling
public class ScheduleConfig implements SchedulingConfigurer {
@Bean("scheduledThreadPoolExecutor")
public Executor scheduledThreadPoolExecutor(a) {
ThreadPoolTaskScheduler scheduler = new ThreadPoolTaskScheduler();
scheduler.setThreadNamePrefix("foxScheduling-");
scheduler.setPoolSize(10);
return scheduler;
}
@Override
public void configureTasks(ScheduledTaskRegistrar scheduledTaskRegistrar) { scheduledTaskRegistrar.setScheduler(scheduledThreadPoolExecutor()); }}Copy the code
For later versions, you only need to modify the configuration
spring:
task:
scheduling:
pool:
# Maximum number of threads, default is 1
size: 10
Scheduling - by default
thread-name-prefix: foxScheduling-
Copy the code
3. Enable or disable the scheduled task
You can configure the switch timing task in the following ways:
1. In-schedule task configuration: ThumbsDown:
This method, which is basically the easiest to find on the web, controls whether to execute the code logic in the scheduled task by injecting the enable value in the configuration file.
@Value("${enable}")
private Boolean enable;
@Scheduled(cron = "${cron:* * * * * ? } ")
public void printLog(a) {
if (enable) {
LOGGER.warn("Perform scheduled tasks"); }}Copy the code
Of course, this approach obviously treats the symptoms rather than the root cause, and the scheduled task is still executed in the background, just without executing the logical code.
2. The annotation@ConditionalOnProperty
👍
This approach is also the most recommended and does not require an upgrade to Spring Boot 2.1 but also requires the enable configuration in YML.
ConditionalOnProperty (” ConditionalOnProperty “, “ConditionalOnProperty”, “ConditionalOnProperty”, “ConditionalOnProperty”, “ConditionalOnProperty”)
@Component
// Runs only when the enable attribute is true, directly reading the contents of the configuration file
@ConditionalOnProperty("enable")
public class ScheduleTask {
private static final Logger LOGGER = LoggerFactory.getLogger(ScheduleTask.class);
@Scheduled(cron = "${cron:* * * * * ? } ")
public void printLog(a) {
LOGGER.warn("Perform scheduled tasks"); }}Copy the code
3. Cron expressions are new in version 2.1
Public static final String CRON_DISABLED = “-“;
To stop a scheduled task, change the value of cron in the configuration file to -.
Configuration contents in the # yML file
cron: The '-'
Copy the code
Note: yML – is the special symbol used to represent the elements of the collection, so you need to use single quotes when configuring it.