@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)); } }
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!