Sub topic 1
Turning on Scheduling
Spring Boot does not run @Scheduled methods by default. You have to switch the feature on once, and after that Spring finds and runs every annotated method in the application context. This chapter covers how to enable scheduling, what happens inside the application when you do, and the common mistakes that leave a task silently idle.
Prerequisites
This chapter assumes you already know:
- The basic structure of a Spring Boot application, including a class annotated with
@SpringBootApplication. - How Spring beans work, and the difference between
@Componentand@Configuration. - How to read
application.propertiesorapplication.yml. - What a thread is, and why two pieces of code running on the same thread cannot run at the same time.
You also need a Spring Boot project with the spring-boot-starter dependency (or any starter that includes it, such as spring-boot-starter-web). Scheduling is part of spring-context, so you do not add a separate dependency.
What @EnableScheduling does
@EnableScheduling is an annotation that tells Spring to look for @Scheduled annotations on beans. Without it, Spring ignores @Scheduled completely. The application starts normally, no error appears, and the method never runs.
The most common place to put it is on 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. The annotation belongs to the application as a whole, so you only need it once.
How it works internally
The annotation imports a configuration class that registers a bean post-processor called ScheduledAnnotationBeanPostProcessor. A bean post-processor is a Spring component that inspects every bean after it is created. This one does the following:
- It looks at each bean's methods for
@Scheduled(and the related@Schedulescontainer). - For each annotated method, it creates a task and a trigger that matches the attributes you set.
- It waits until the context has finished refreshing. Then it hands all tasks to a task scheduler so they start running.
Two consequences follow from this:
- Only Spring-managed beans are scanned. A
@Scheduledmethod on an object you create withnewis never found. - Tasks do not start while the context is still being built. They start after the application context refresh completes, so beans a task depends on are fully initialized by then.
Where to place the annotation
You can put @EnableScheduling on any @Configuration class that Spring loads. There are two reasonable choices.
| Placement | Advantage | Drawback |
|---|---|---|
| Main application class | Simple, one line, easy to find | Mixes feature switches into the entry point |
| Dedicated `@Configuration` class | Easy to exclude or replace in tests | One more class to maintain |
A dedicated class looks like this:
import org.springframework.context.annotation.Configuration;
import org.springframework.scheduling.annotation.EnableScheduling;
@Configuration
@EnableScheduling
public class SchedulingConfig {
}The dedicated class is the better choice for most real applications. Later chapters show how tests can load a slice of the application without this class, so that scheduled jobs do not fire during unrelated tests.
A first working task
With scheduling enabled, add a bean with one annotated method:
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("heartbeat on thread {}", Thread.currentThread().getName());
}
}Start the application. About every five seconds you should see a log line like this:
heartbeat on thread scheduling-1The thread name scheduling-1 is the default prefix Spring Boot uses for its auto-configured scheduler. Note that it is -1 every time. The default pool has a single thread, which matters when you run several tasks. Chapter content on the thread pool comes later in this tutorial, but keep this fact in mind: two tasks that are due at the same moment run one after the other, not together.
Requirements for a scheduled method
Spring is strict about what it will schedule. A @Scheduled method must:
- Be on a Spring bean.
- Return
void. Any return value is ignored. Spring Boot and Spring Framework in recent versions may reject or warn about non-void methods, depending on the version, so treatvoidas the rule. - Take no arguments. Spring has nothing to pass in, so a method with parameters fails at startup.
If a method breaks these rules, the application context fails to start with an IllegalStateException. That is useful. It means a wrong signature shows up immediately, not at 02:00 on a Sunday.
Also note the visibility: a private method on a class that Spring proxies can cause trouble, so use public or package-private methods on ordinary beans. Keep the method body short and move real logic to a separate service. That makes it easy to test, which a later chapter covers.
How Boot provides the scheduler
Enabling scheduling does not create the scheduler by itself. Spring Boot's auto-configuration creates a ThreadPoolTaskScheduler bean when it detects @EnableScheduling and finds no other scheduler bean. This is why a plain Boot application works with no further setup, while a plain Spring Framework application must define its own scheduler or accept a fallback.
If you do not define a scheduler, the post-processor looks for one in this order:
- A
TaskSchedulerbean in the context. Boot supplies one here. - A
ScheduledExecutorServicebean. - If neither exists, it creates a local single-threaded executor of its own.
You can customize the auto-configured one through properties such as spring.task.scheduling.pool.size. The next chapters cover those settings in detail.
Common mistakes
These are the problems that most often make a task appear to do nothing.
- Missing
@EnableScheduling. The log stays quiet and nothing reports an error. Check this first. - Annotated class is not a bean. A class without
@Component,@Serviceor similar is not scanned, so its@Scheduledmethods are never found. - Class is outside the component scan. Spring Boot scans the package of the main class and its sub-packages. A bean in a sibling package is not found unless you widen the scan.
- Wrong method signature. Arguments or an unsupported return type stop the application from starting.
- Scheduling disabled in a test or profile. If you moved
@EnableSchedulinginto a configuration class guarded by@Profileor@ConditionalOnProperty, tasks stop when that condition is false. - Application exits too early. A command-line app with no web server may end
mainbefore the first run. A web starter keeps the JVM alive, while a plain starter may not.
Switching scheduling on and off with a property
A useful pattern is to let configuration decide whether scheduling is active. This lets you turn off background jobs in a local run or in a test profile without editing code.
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 because of matchIfMissing = true. Setting app.scheduling.enabled=false in a profile removes the whole configuration, so no @Scheduled method on any bean runs.
# application-test.yml
app:
scheduling:
enabled: falseChecking that tasks are registered
When a task seems to be missing, you can ask Spring what it registered. The post-processor exposes its tasks, and Spring Boot Actuator shows them through the scheduledtasks endpoint when the Actuator dependency is present and the endpoint is exposed.
management:
endpoints:
web:
exposure:
include: scheduledtasksA request to /actuator/scheduledtasks returns JSON that groups tasks by type: cron, fixedDelay, fixedRate and custom. A task listed there is registered. A task missing from the list was never found, which points back to the mistakes above.
Setting the logger org.springframework.scheduling to DEBUG also helps, because it records when the scheduler starts and stops.
Summary of the setup
- Add
@EnableSchedulingonce, on the main class or a configuration class. - Declare each task as a
public voidmethod with no arguments on a Spring bean. - Spring Boot supplies a single-threaded scheduler unless you configure otherwise.
- Tasks start after the context is fully refreshed.
- Missing configuration fails silently, so verify with logs or the Actuator endpoint.
Exercise
A developer adds a @Component class with a method annotated @Scheduled(fixedRate = 2000). The application starts without errors, but the method never runs. Name the most likely cause, and name one other cause that would give the same symptom.
Show answer
The most likely cause is that @EnableScheduling is missing, so Spring ignores @Scheduled and reports nothing. Another cause with the same symptom is that the class is outside the component scan of the main class's package, so it never becomes a bean and is never inspected. A configuration guard such as @ConditionalOnProperty that evaluates to false would also match.
Exercise
You enable scheduling through a dedicated SchedulingConfig class guarded by @ConditionalOnProperty(name = "app.scheduling.enabled", havingValue = "true", matchIfMissing = true). What happens in a test profile that sets app.scheduling.enabled=false, and what happens in a profile that does not set the property at all?
Show answer
With the property set to false, the condition fails, the configuration class is not loaded, and no @Scheduled method on any bean runs. With the property absent, matchIfMissing = true makes the condition pass, so scheduling stays enabled.