Sub topic 1
Turning on scheduling
Spring Boot does not run @Scheduled methods unless you ask it to. This chapter shows the one annotation that switches scheduling on, what it does inside the application context, and the mistakes that leave a task silently idle.
Prerequisites
This chapter assumes you already know:
- The basic structure of a Spring Boot application, including a main class annotated with
@SpringBootApplication. - How Spring beans work, and the difference between
@Componentand@Configuration. - How to read settings from
application.propertiesorapplication.yml. - What a thread is, and that two pieces of code can run at the same time.
Why scheduling is off by default
Spring Boot's auto-configuration sets up many features for you. Scheduling is not one of them. Running code on a timer changes how an application behaves, because it starts background threads that run without any request. Spring therefore makes you opt in.
The opt-in is the @EnableScheduling annotation. Without it, a method marked @Scheduled compiles and the application starts without errors, but the method never runs.
Adding @EnableScheduling
Place the annotation on any class that Spring treats as configuration. The usual place is the main application class.
import org.springframework.boot.SpringApplication;
import org.springframework.boot.autoconfigure.SpringBootApplication;
import org.springframework.scheduling.annotation.EnableScheduling;
@SpringBootApplication
@EnableScheduling
public class Application {
public static void main(String[] args) {
SpringApplication.run(Application.class, args);
}
}@EnableScheduling activates processing of @Scheduled annotations on all beans in the application context. It does not matter which configuration class carries it. One occurrence is enough for the whole application.
What happens at startup
The annotation imports a post-processor, a bean that Spring runs over every other bean as the context is built. The sequence is:
- Spring creates your beans as usual.
- The scheduling post-processor inspects each bean for methods annotated with
@Scheduled. - For each such method, it registers a task with a scheduler.
- When the context has finished refreshing, the scheduler starts triggering the tasks.
Spring Boot supplies the scheduler itself. Its auto-configuration creates a scheduler bean once scheduling is enabled. By default this scheduler has a single thread, a limit that later chapters cover.
placeholderChecking that it works
A minimal task confirms the setup. This bean logs a message every five seconds.
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.scheduling.annotation.Scheduled;
import org.springframework.stereotype.Component;
@Component
public class HeartbeatJob {
private static final Logger log = LoggerFactory.getLogger(HeartbeatJob.class);
@Scheduled(fixedRate = 5000)
public void beat() {
log.info("scheduler is running");
}
}Start the application. You should see the log line about every five seconds. The thread name in the log output is scheduling-1, which shows the line came from the scheduler thread and not from a web request.
Common errors
The task never runs. Check these causes first:
- Missing
@EnableScheduling. This is the most common cause, and nothing in the log points to it. - The class is not a Spring bean. Spring only scans beans. A plain
new HeartbeatJob()is never registered, and a class without@Componentis never created. - The method signature is wrong. A scheduled method must return
voidand take no arguments. Spring rejects other signatures when the context starts. - The application exits too soon. A command-line application or a test can end before the first trigger. Web applications stay alive, so this mostly affects small demos.
Keeping scheduling switchable
Because scheduling is a single switch, you can make it conditional. A separate configuration class keeps the switch out of the main class.
import org.springframework.boot.autoconfigure.condition.ConditionalOnProperty;
import org.springframework.context.annotation.Configuration;
import org.springframework.scheduling.annotation.EnableScheduling;
@Configuration
@EnableScheduling
@ConditionalOnProperty(
name = "app.scheduling.enabled",
havingValue = "true",
matchIfMissing = true)
public class SchedulingConfig {
}With this class, scheduling is on by default. Setting app.scheduling.enabled=false turns off every scheduled task in that environment. Remove @EnableScheduling from the main class if you use this approach, or the switch has no effect.
Exercise
A developer adds a @Scheduled(fixedRate = 1000) method to a class annotated with @Component. The application starts without errors, but the method never runs. What is the most likely cause, and how do you fix it?
Show answer
@EnableScheduling is missing. Add it to the main application class or to a @Configuration class so that Spring processes @Scheduled annotations.
Exercise
You use the conditional SchedulingConfig class above but also left @EnableScheduling on the main class. You set app.scheduling.enabled=false. Do tasks still run?
Show answer
Yes. The annotation on the main class still enables scheduling, so the property has no effect. Remove it from the main class.