Working with Scheduled Tasks

1. Enabling Scheduling (@EnableScheduling)

Example: Enable task scheduling

@SpringBootApplication
@EnableScheduling
public class App {}

2. Creating Scheduled Methods (@Scheduled)

Attribute Format
fixedRate ms between starts
fixedDelay ms between end and next start
fixedRateString Property placeholder support
initialDelay Delay before first run
cron Cron expression
zone Timezone for cron

3. Using Fixed Rate Execution

Example: Fixed-rate scheduled task

@Scheduled(fixedRate = 60_000)
public void every60s() { /* every 60s regardless of duration */ }

4. Using Fixed Delay Execution

Example: Fixed-delay with initial delay

@Scheduled(fixedDelay = 5000, initialDelay = 10_000)
public void backoff() { /* 5s after previous completion */ }

5. Using Cron Expressions

Field Range
second 0–59
minute 0–59
hour 0–23
day-of-month 1–31
month 1–12 / JAN-DEC
day-of-week 0–7 / MON-SUN

Example: Cron expressions with timezone

@Scheduled(cron = "0 0 2 * * *", zone = "UTC")  // every day 02:00 UTC
@Scheduled(cron = "0 */5 * * * MON-FRI")        // every 5 min on weekdays
@Scheduled(cron = "${app.cron.cleanup:0 0 * * * *}")

6. Configuring Initial Delay

Attribute Notes
initialDelay Wait period before first run (ms)
initialDelayString Property placeholder

7. Using Dynamic Scheduling (SchedulingConfigurer)

Example: Dynamic cron from configuration

@Configuration
@EnableScheduling
public class DynamicSchedule implements SchedulingConfigurer {
  @Override public void configureTasks(ScheduledTaskRegistrar registrar) {
    registrar.addTriggerTask(
      () -> doWork(),
      ctx -> new CronTrigger(props.getCron()).nextExecution(ctx)
    );
  }
}

8. Configuring Task Scheduler Pool Size

Example: Scheduler pool size configuration

spring:
  task:
    scheduling:
      pool:
        size: 4
      thread-name-prefix: scheduler-
Warning: Default pool size = 1 → long-running task blocks all others. Increase for concurrent schedules.

9. Handling Scheduled Task Exceptions

Example: Safe scheduled task with error logging

@Scheduled(fixedRate = 60_000)
public void safeRun() {
  try { work(); }
  catch (Exception ex) { log.error("scheduled failure", ex); }
}
Note: Uncaught exceptions don't stop schedule but are silently logged at WARN — handle explicitly.

10. Using Time Zones in Cron Expressions

Setting Effect
zone="UTC" Cron evaluated in UTC
zone="America/New_York" Local DST aware
Default JVM default time zone

11. Testing Scheduled Tasks

Strategy How
Disable in tests @MockBean the scheduled bean OR set spring.task.scheduling.enabled=false
Manual invoke Call the method directly in unit test
Awaitility Wait for side effects