springboot timing task does not work
When I wrote another timed task today, I found that all the configurations were fine, but the timed task was not executed. Through various comparison tests and exclusion methods, I finally found the problem.
Let's take a look at the startup class below
@SpringBootApplication @ComponentScan(value = ".timer_demo",lazyInit = true) @EnableScheduling public class TimerDemoApplication { public static void main(String[] args) { (, args); } }
There are three annotations on the startup class
One of the annotations is that there is a lazyInit attribute, what does it mean?
The default behavior of ApplicationContext implementation is to instantiate all singleton beans in advance when starting the server (that is, dependency injection).
Early instantiation means that as part of the initialization process, the applicationContext instance creates and configures all singleton beans.
This is usually a good thing because any errors in the configuration will be implemented immediately.
Delay loading, beans set to lazy = true will not be instantiated in advance when ApplicationContext starts, but will be instantiated when the bean is requested from the container through the getBean for the first time.
This explanation means:
When this property is true, the bean class will be delayed loading. In that case, the timing task class is not loaded at startup, and it will naturally not be able to execute the timing task. How to solve it at this time?
You can't remove this property of the previous startup class. Adding this to the startup class requires the senior master to consider it yourself. It's better not to move, so specify that some classes do not use delayed loading.
The code is as follows:
@Component @Lazy(false) public class MyTimerTest { // means every 1 second @Scheduled(fixedRate=1000) public void clearData(){ ("Timed Task"+()); } }
If you want to make any class load without lazily, add the @Lazy(false) annotation
OK, springboot's lazy loading pit will be solved
Summarize
The above is personal experience. I hope you can give you a reference and I hope you can support me more.