Sub topic 11
Registering tasks in code with SchedulingConfigurer
This chapter assumes you can already declare tasks with @Scheduled, and that you know fixedRate, fixedDelay and cron triggers. It also assumes you know that Spring Boot's scheduler uses one thread unless you configure it. Here you will register the same kinds of tasks from Java code. You will also supply your own scheduler and build a trigger whose timing can change at runtime.
Why register tasks in code
@Scheduled fixes a task's timing when the application starts. Annotation attributes must be compile-time constants or property placeholders. The placeholders are resolved once, at startup. That is enough for most jobs. Programmatic registration helps when:
- the number of tasks is not known until runtime, for example one task per tenant read from a database;
- the schedule must change while the application runs, for example when an operator edits an interval;
- you want one place that configures both the tasks and the scheduler that runs them;
- the task is a lambda or a third-party object that you cannot annotate.
The tool is the SchedulingConfigurer interface. It has one method, configureTasks(ScheduledTaskRegistrar). Spring calls it once during startup. Anything you register on the registrar is scheduled alongside the @Scheduled methods.
How the pieces connect
The configurer only describes the work. The registrar schedules it after every configurer has run. The task scheduler owns the threads.
Registering the basic trigger types
The registrar has one method for each trigger style you know from @Scheduled.
import org.springframework.context.annotation.Configuration;
import org.springframework.scheduling.annotation.EnableScheduling;
import org.springframework.scheduling.annotation.SchedulingConfigurer;
import org.springframework.scheduling.config.ScheduledTaskRegistrar;
@Configuration
@EnableScheduling
public class ProgrammaticSchedulingConfig implements SchedulingConfigurer {
private final CleanupService cleanup;
public ProgrammaticSchedulingConfig(CleanupService cleanup) {
this.cleanup = cleanup;
}
@Override
public void configureTasks(ScheduledTaskRegistrar registrar) {
// like fixedRate = 60000
registrar.addFixedRateTask(cleanup::purgeSessions, 60_000);
// like fixedDelay = 30000
registrar.addFixedDelayTask(cleanup::retryFailed, 30_000);
// like cron = "0 */5 * * * *" (six fields, as with @Scheduled)
registrar.addCronTask(cleanup::compact, "0 */5 * * * *");
}
}import org.springframework.stereotype.Service;
@Service
public class CleanupService {
public void purgeSessions() { /* delete expired sessions */ }
public void retryFailed() { /* retry failed deletions */ }
public void compact() { /* compact storage */ }
}Three details to note:
- The interval arguments are milliseconds. In recent Spring versions there are also overloads that take a
Duration, which is harder to misread. - Cron strings use Spring's six-field format, the same as
@Scheduled. There is no time zone argument on the string overload. For a specific zone, build aCronTrigger(shown below). - A task is a plain
Runnable. Keep the logic in a service bean, as above, so you can test it without the scheduler.
Choosing the scheduler
The registrar needs a TaskScheduler to run tasks. You can give it one explicitly.
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.scheduling.TaskScheduler;
import org.springframework.scheduling.annotation.EnableScheduling;
import org.springframework.scheduling.annotation.SchedulingConfigurer;
import org.springframework.scheduling.concurrent.ThreadPoolTaskScheduler;
import org.springframework.scheduling.config.ScheduledTaskRegistrar;
@Configuration
@EnableScheduling
public class SchedulerConfig implements SchedulingConfigurer {
@Bean
public ThreadPoolTaskScheduler taskScheduler() {
ThreadPoolTaskScheduler scheduler = new ThreadPoolTaskScheduler();
scheduler.setPoolSize(4);
scheduler.setThreadNamePrefix("sched-");
scheduler.setWaitForTasksToCompleteOnShutdown(true);
scheduler.setAwaitTerminationSeconds(30);
scheduler.setErrorHandler(t ->
org.slf4j.LoggerFactory.getLogger("scheduler").error("Scheduled task failed", t));
return scheduler;
}
@Override
public void configureTasks(ScheduledTaskRegistrar registrar) {
registrar.setTaskScheduler(taskScheduler());
}
}Calling taskScheduler() inside a @Configuration class returns the same singleton bean, because Spring proxies the class. The scheduler's lifecycle is then managed by the container, including shutdown.
This is the most common surprise with this interface. A team adds a configurer for one dynamic task and finds that all their @Scheduled methods are back on one thread.
| Aspect | `@Scheduled` only | With a `SchedulingConfigurer` |
|---|---|---|
| Boot-configured scheduler | Yes, from `spring.task.scheduling.*` | No, you supply one |
| Default threads if you do nothing else | 1 | 1 (local executor) |
| Timing known at | Startup | Startup, or each run with a trigger |
| Number of tasks | Fixed by code | Can be computed |
Time zones and custom triggers with TriggerTask
For anything beyond a fixed rate or a plain cron string, use addTriggerTask(Runnable, Trigger). A Trigger answers one question: when should this task run next? Spring asks after every run.
A cron task in a specific zone:
import java.time.ZoneId;
import org.springframework.scheduling.support.CronTrigger;
@Override
public void configureTasks(ScheduledTaskRegistrar registrar) {
registrar.addTriggerTask(
cleanup::compact,
new CronTrigger("0 0 2 * * *", ZoneId.of("Europe/Berlin")));
}An interval that can change while the application runs:
import java.time.Duration;
import java.time.Instant;
import java.util.concurrent.atomic.AtomicReference;
import org.springframework.scheduling.Trigger;
import org.springframework.scheduling.TriggerContext;
@Configuration
@EnableScheduling
public class DynamicSchedulingConfig implements SchedulingConfigurer {
private final AtomicReference<Duration> interval =
new AtomicReference<>(Duration.ofSeconds(30));
private final CleanupService cleanup;
public DynamicSchedulingConfig(CleanupService cleanup) {
this.cleanup = cleanup;
}
public void changeInterval(Duration newInterval) {
interval.set(newInterval);
}
@Override
public void configureTasks(ScheduledTaskRegistrar registrar) {
registrar.addTriggerTask(cleanup::purgeSessions, new Trigger() {
@Override
public Instant nextExecution(TriggerContext context) {
Instant last = context.lastCompletion();
Instant base = (last != null) ? last : Instant.now();
return base.plus(interval.get());
}
});
}
}Here is how this works:
- On the first call,
lastCompletion()isnull, so the trigger counts from now. - After each run, the trigger counts from the completion time, which gives fixed-delay behavior.
- The interval is read on every call. A new value takes effect after the run currently scheduled, not immediately.
Returning null from nextExecution tells the scheduler not to run the task again. That is how a trigger can end itself.
Cancelling and rescheduling
addTriggerTask and the other add methods return nothing you can cancel, because the registrar schedules tasks later. To get a handle at runtime, inject a TaskScheduler and call it directly:
import java.time.Duration;
import java.util.concurrent.ScheduledFuture;
import org.springframework.scheduling.TaskScheduler;
import org.springframework.stereotype.Component;
@Component
public class ManagedJob {
private final TaskScheduler scheduler;
private final CleanupService cleanup;
private ScheduledFuture<?> handle;
public ManagedJob(TaskScheduler scheduler, CleanupService cleanup) {
this.scheduler = scheduler;
this.cleanup = cleanup;
}
public synchronized void start(Duration period) {
stop();
handle = scheduler.scheduleAtFixedRate(cleanup::purgeSessions, period);
}
public synchronized void stop() {
if (handle != null) {
handle.cancel(false);
handle = null;
}
}
}cancel(false) lets a run that is already in progress finish. Pass true only if the task handles interruption. This approach needs a TaskScheduler bean. Boot supplies one if no configurer is present. Otherwise use the bean from the previous section.
Common mistakes
- Forgetting
@EnableScheduling, soconfigureTasksnever runs. - Passing seconds where the registrar expects milliseconds.
- Registering the same task twice, once by annotation and once in code, so it runs twice per period.
- Expecting
spring.task.scheduling.pool.sizeto apply after adding a configurer. - Changing a mutable value in a trigger from several threads without a thread-safe holder such as
AtomicReference. - Letting exceptions out of a
Trigger. IfnextExecutionthrows, the task stops being rescheduled.
Exercise
You add a SchedulingConfigurer to register one extra cron task. Afterwards, your existing @Scheduled methods run one at a time even though application.yml sets spring.task.scheduling.pool.size to 4. Why does this happen, and what is the fix?
Show answer
A SchedulingConfigurer bean makes Spring Boot skip its auto-configured TaskScheduler, so the spring.task.scheduling.* properties are no longer applied. The registrar falls back to a single-thread executor. The fix is to define a ThreadPoolTaskScheduler bean with the pool size you want and call registrar.setTaskScheduler(...) in configureTasks. Alternatively, remove the configurer.
Exercise
A trigger's nextExecution method returns null after a run. What does the scheduler do with the task?
Show answer
It does not schedule the task again. Returning null ends the task's schedule.