Sub topic 11
Registering tasks in code with SchedulingConfigurer
@Scheduled fixes a schedule at compile time. Sometimes you need to build the schedule in Java: the interval comes from a database, the tasks are generated in a loop, or you want to supply your own scheduler. SchedulingConfigurer covers these cases. This chapter assumes you know @EnableScheduling, the @Scheduled trigger types, and how the scheduler thread pool works.
How the configurer fits in
When scheduling starts, Spring calls configureTasks on every SchedulingConfigurer bean. It passes in a ScheduledTaskRegistrar. You add tasks to the registrar, and you can replace the scheduler it uses. Annotated methods are registered with the same registrar, so both styles can run side by side.
The registrar methods
| Method | Equivalent annotation |
|---|---|
| `addCronTask(Runnable, String)` | `@Scheduled(cron = ...)` |
| `addFixedRateTask(Runnable, long)` | `@Scheduled(fixedRate = ...)` |
| `addFixedDelayTask(Runnable, long)` | `@Scheduled(fixedDelay = ...)` |
| `addTriggerTask(Runnable, Trigger)` | No annotation equivalent |
The last row is the reason to use code. A Trigger computes the next run time each time the task finishes, so the interval can change while the application runs.
A complete example
This configuration uses its own named scheduler and registers two tasks. One is a fixed cron task. The other recomputes its delay from a property on every run.
import java.time.Instant;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
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 ProgrammaticSchedulingConfig implements SchedulingConfigurer {
private static final Logger log =
LoggerFactory.getLogger(ProgrammaticSchedulingConfig.class);
private final ThreadPoolTaskScheduler scheduler;
private final long intervalSeconds;
public ProgrammaticSchedulingConfig(
ThreadPoolTaskScheduler scheduler,
@Value("${report.interval-seconds:10}") long intervalSeconds) {
this.scheduler = scheduler;
this.intervalSeconds = intervalSeconds;
}
@Bean
static ThreadPoolTaskScheduler taskScheduler() {
ThreadPoolTaskScheduler s = new ThreadPoolTaskScheduler();
s.setPoolSize(4);
s.setThreadNamePrefix("code-sched-");
return s;
}
@Override
public void configureTasks(ScheduledTaskRegistrar registrar) {
registrar.setTaskScheduler(scheduler);
registrar.addCronTask(
() -> log.info("cron task"),
"0 */5 * * * *");
registrar.addTriggerTask(
() -> log.info("dynamic task"),
triggerContext -> {
Instant last = triggerContext.lastCompletion();
Instant base = last != null ? last : Instant.now();
return base.plusSeconds(intervalSeconds);
});
}
}The trigger returns an Instant. On the first call lastCompletion() is null, so the code falls back to the current time. Returning null from a trigger ends the task for good, which is useful for a one-off job.
Common errors
- Forgetting
@EnableScheduling. The configurer bean is created, but nothing runs. - Building the scheduler by hand without a bean. A
ThreadPoolTaskSchedulercreated withnewinsideconfigureTasksmust haveinitialize()called. Declaring it as a@Bean, as above, lets Spring do that. - Expecting
spring.task.scheduling.*to apply. Those properties configure Boot's auto-configured scheduler. Your own scheduler bean replaces it, so set pool size and thread names in code. - Letting exceptions escape. A thrown exception is logged and the next run still happens, as with
@Scheduled. For a trigger task, an exception thrown inside theTriggeritself is a bug in your scheduling logic, so keep that code simple.
Exercise
A task registered with addTriggerTask should run 30 seconds after the previous run finishes. Which TriggerContext method gives you the reference time, and what must you handle on the first run?
Show answer
Use triggerContext.lastCompletion() and add 30 seconds to it. On the first run it returns null, so fall back to Instant.now() (or another start time) before adding the delay.