Sub topic 5
Moving schedules into configuration
This chapter assumes you can write a @Scheduled method, you know the difference between fixedRate, fixedDelay and cron, and you have used application.yml or application.properties. Here you will move schedule values out of the annotations and into configuration, so each environment can set its own timing without a code change.
Why hard-coded schedules cause trouble
A literal value such as @Scheduled(cron = "0 0 3 * * *") is fixed at compile time. That causes three common problems:
- A job that should run every night in production runs every five seconds in a developer's local run, or the reverse.
- Changing the timing means rebuilding and redeploying.
- Integration tests cannot slow a job down or turn it off without editing the source.
Spring solves this by letting the annotation attributes take property placeholders, the same ${...} syntax used by @Value.
String attributes accept placeholders
The numeric attributes fixedRate, fixedDelay and initialDelay are long values, and a long cannot hold a placeholder. Each one has a String twin that can:
| Numeric attribute | String attribute | Accepts |
|---|---|---|
| `fixedRate` | `fixedRateString` | milliseconds, ISO-8601 duration, placeholder |
| `fixedDelay` | `fixedDelayString` | milliseconds, ISO-8601 duration, placeholder |
| `initialDelay` | `initialDelayString` | milliseconds, ISO-8601 duration, placeholder |
| `cron` | `cron` | cron expression, placeholder |
| `zone` | `zone` | zone ID, placeholder |
cron and zone are already String attributes, so they accept placeholders directly. Use either the numeric or the String form of an attribute in one annotation, not both, because Spring rejects the combination.
@Component
public class CleanupJob {
@Scheduled(cron = "${cleanup.cron:0 0 3 * * *}")
public void cleanup() {
// delete expired records
}
@Scheduled(fixedDelayString = "${cleanup.retry-delay:PT30S}")
public void retry() {
// retry failed deletions
}
}The text after the first colon in a placeholder is the default. If cleanup.cron is not defined anywhere, Spring uses 0 0 3 * * *, which means every day at 03:00. Because the default sits next to the code, a missing property does not stop the application from starting.
Duration formats
A String attribute can hold either of these:
- Plain milliseconds, such as
5000. - An ISO-8601 duration, such as
PT30S(30 seconds),PT5M(5 minutes) orPT1H(1 hour).
ISO-8601 durations are easier to read and harder to get wrong by a factor of 1000. Recent Spring versions also accept the simple style such as 30s, 5m, 1h, but ISO-8601 works in every version, so it is the safer choice for shared examples.
Supplying the values
The properties go in the normal configuration files.
cleanup:
cron: "0 0 3 * * *"
retry-delay: PT30SQuote cron expressions in YAML. A bare 0 0 3 * * * is usually read as a string, but an expression that starts with * is read as a YAML alias and fails to parse. Quoting removes that risk.
Profile-specific files let each environment override a value:
# application-dev.yml
cleanup:
cron: "0 */1 * * * *"
retry-delay: PT5SRunning with --spring.profiles.active=dev then makes cleanup run every minute and retries after 5 seconds, while production keeps the defaults. Environment variables work too. Spring's relaxed binding is not applied to ${...} placeholders in the same way as to @ConfigurationProperties, so for a property named cleanup.retry-delay the most reliable environment variable form is CLEANUP_RETRYDELAY or the exact property name supplied through SPRING_APPLICATION_JSON or a command-line argument such as --cleanup.retry-delay=PT10S. Test whichever form you rely on.
Disabling a job
A schedule cannot be switched off by leaving a property empty, and a blank value for cron or a duration fails when the bean is created. Spring defines one special value for this: - (a single dash) in the cron attribute disables the trigger.
@Scheduled(cron = "${cleanup.cron:-}")
public void cleanup() {
// runs only when cleanup.cron is set to a real expression
}With this setup the job is off by default. Setting cleanup.cron to a real expression turns it on. The constant Scheduled.CRON_DISABLED holds the same - value for use in Java code. This works only for cron, not for fixedRate or fixedDelay.
To switch off a whole class of jobs, use a condition on the bean instead:
@Component
@ConditionalOnProperty(name = "jobs.cleanup.enabled", havingValue = "true")
public class CleanupJob {
@Scheduled(cron = "${cleanup.cron:0 0 3 * * *}")
public void cleanup() {
// delete expired records
}
}When jobs.cleanup.enabled is not true, Spring does not create the bean, so it registers no task at all. This is also the clearest way to keep jobs off in tests and on instances that should not run them.
Grouping settings with @ConfigurationProperties
Many jobs mean many property names. Binding them to one typed class keeps related values together and gives you validation:
@ConfigurationProperties(prefix = "cleanup")
public record CleanupProperties(String cron, Duration retryDelay) {
}A placeholder in @Scheduled can still read the same keys, but there is a limit. Annotation attributes are evaluated once, when the bean is post-processed, and they need strings. They cannot call a method on a properties object directly. A SpEL expression can reach a bean by name, as in #{@cleanupProperties.cron()}, but this requires a known bean name, and @ConfigurationProperties beans registered through @EnableConfigurationProperties get a long generated name that includes the prefix. For that reason, plain ${...} placeholders are the simpler choice for schedule attributes, and @ConfigurationProperties is better for the job's own settings, such as batch size or retention period.
When the value is read
Placeholders are resolved once, at startup, when Spring registers the task. Changing a property later, for example through a refreshed environment, does not change a running schedule. To apply a new value you restart the application, or you register the task in code and rebuild it when the setting changes. Chapter 11 covers SchedulingConfigurer for that approach.
Because resolution happens at startup, a bad value fails fast. An invalid cron expression or an unparsable duration stops the application context from starting, with a message that names the offending value. That is better than a job that silently never runs.
Common mistakes
- Using
fixedRatewith a placeholder.@Scheduled(fixedRate = "${x}")does not compile. UsefixedRateString. - Setting both forms. Using
fixedDelayandfixedDelayStringtogether on one method fails at startup. - Forgetting the default.
${cleanup.cron}with no default and no property stops the application. That may be what you want in production, but it surprises people in tests. - Unquoted cron in YAML. Expressions that start with
*can break parsing. Quote them. - Mixing units.
5000means milliseconds, andPT5000Smeans about 83 minutes. Check the form you wrote. - Expecting live reload. Editing a property at runtime does not reschedule the task.
Exercise
A job must run every 10 minutes in production, every 10 seconds in the dev profile, and must be disabled in the test profile. Using fixedDelay, which attribute and which property setup do you use? State what you put in each profile.
Show answer
Use fixedDelayString, because only the String attribute takes a placeholder: @Scheduled(fixedDelayString = "${sync.delay:PT10M}"). Production needs no setting because the default is 10 minutes. In application-dev.yml set sync.delay: PT10S. fixedDelay has no disable value like the cron -, so for test put @ConditionalOnProperty(name = "sync.enabled", havingValue = "true", matchIfMissing = true) on the class and set sync.enabled: false in application-test.yml. The bean is then not created in tests, so no task is registered.
Exercise
You change cleanup.cron in a running application's environment, but the job keeps its old timing. Why, and what are two ways to get the new timing?
Show answer
Spring resolves the placeholder once at startup, when it registers the task, so later changes do not reschedule it. You can restart the application, or register the task in code with SchedulingConfigurer and rebuild it when the setting changes.