Home > Java > javaTutorial > body text

How to solve the problem of scheduled tasks not being executed in schedule in springboot

WBOY
Release: 2023-05-13 21:10:12
forward
2414 people have browsed it

@schedule annotation is a commonly used scheduled task annotation in springboot. It is simple and convenient to use. However, if there are many scheduled tasks, or some tasks are very time-consuming, it will affect the execution of other scheduled tasks, because schedule is single-threaded by default. , when a task is executed, other tasks cannot be executed. The solution is to reconfigure the schedule and change it to multi-thread execution. Just add the following configuration class.

import org.springframework.boot.autoconfigure.batch.BatchProperties;
import org.springframework.context.annotation.Configuration;
import org.springframework.scheduling.annotation.Scheduled;
import org.springframework.scheduling.annotation.SchedulingConfigurer;
import org.springframework.scheduling.config.ScheduledTaskRegistrar;
import java.lang.reflect.Method;
import java.util.concurrent.Executors;
@Configuration
public class ScheduleConfig implements SchedulingConfigurer {
  @Override
  public void configureTasks(ScheduledTaskRegistrar taskRegistrar) {
    Method[] methods = BatchProperties.Job.class.getMethods();
    int defaultPoolSize = 3;
    int corePoolSize = 0;
    if (methods != null && methods.length > 0) {
      for (Method method : methods) {
        Scheduled annotation = method.getAnnotation(Scheduled.class);
        if (annotation != null) {
          corePoolSize++;
        }
      }
      if (defaultPoolSize > corePoolSize)
        corePoolSize = defaultPoolSize;
    }
    taskRegistrar.setScheduler(Executors.newScheduledThreadPool(corePoolSize));
  }
}
Copy after login

The above is the detailed content of How to solve the problem of scheduled tasks not being executed in schedule in springboot. For more information, please follow other related articles on the PHP Chinese website!

Related labels:
source:yisu.com
Statement of this Website
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn
Popular Tutorials
More>
Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template