Spring scheduling: how @Scheduled runs tasks and where it goes wrong

One annotation turns a Spring bean method into a recurring task, but the trigger, the scheduler's threads and the number of running instances decide what really happens. This page explains each part and runs every important case with Spring Framework 7.0, from a slow task that blocks all others to a cron job that daylight saving time runs twice.

Contents

How Spring runs scheduled tasks

Many applications have work that runs on a clock rather than on a request: clean up expired sessions every 10 minutes, send invoices at 02:00, poll a partner API every 30 seconds. Spring's scheduling support turns a bean method into such a task with one annotation, @Scheduled.

Three pieces are involved:

  • The annotation processor: @EnableScheduling registers ScheduledAnnotationBeanPostProcessor. As each bean is created, it finds the @Scheduled methods and turns each one into a task with a trigger.
  • The trigger: it decides when the next run happens. A fixed rate counts from the start of the previous run, a fixed delay from its end, and a cron expression from the calendar.
  • The TaskScheduler: a pool of threads that waits for each trigger time and runs the task. Spring uses a TaskScheduler or ScheduledExecutorService bean if there is one. Otherwise it creates a scheduler with a single thread, so all tasks share one thread.

The single default thread is the source of most scheduling surprises. A slow task delays every other task, and a task never runs twice at the same time, whatever the rate says. Both are shown running below.

Ways to schedule work in Spring
OptionSinceWhen the next run startsBest for
@Scheduled(fixedRate = ...)3.0A fixed time after the previous startHeartbeats and metrics that should keep a steady pace
@Scheduled(fixedDelay = ...)3.0A fixed time after the previous endPolling and clean-up, where runs must not pile up
@Scheduled(cron = ...)3.0The next time that matches the expressionCalendar times: 02:00 daily, the last weekday of the month
timeUnit attribute5.3.10Sets the unit for rate, delay and initial delayfixedDelay = 30, timeUnit = TimeUnit.SECONDS
TaskScheduler with a Trigger3.0Whatever your code computesSchedules decided at run time, such as backoff
SimpleAsyncTaskScheduler6.1Runs each task on a new thread, which may be virtualApplications on Java 21 or later with virtual threads

Spring Framework 6.1 also added @Scheduled on methods that return a reactive Publisher, and a scheduler attribute that picks a named scheduler bean. Every program on this page runs Spring Framework 7.0 without Spring Boot. Programs that measure time round to the nearest 100 ms or print a yes-or-no result, because the exact milliseconds differ on every run.

fixedRate and fixedDelay

The two interval settings sound alike and behave differently as soon as a task takes time. Here both use 500 ms, and each run sleeps for 300 ms to stand in for real work. A scheduler with 2 threads lets the two tasks run independently:

Java
import java.util.List;
import java.util.concurrent.CopyOnWriteArrayList;
import java.util.concurrent.CountDownLatch;
import java.util.concurrent.TimeUnit;
import org.springframework.context.annotation.AnnotationConfigApplicationContext;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.scheduling.annotation.EnableScheduling;
import org.springframework.scheduling.annotation.Scheduled;
import org.springframework.scheduling.concurrent.ThreadPoolTaskScheduler;

public class RateVsDelay {

    static final CountDownLatch DONE = new CountDownLatch(10);

    static void work(List<Long> starts) {
        if (starts.size() == 5) {
            return;
        }
        starts.add(System.nanoTime());
        try {
            Thread.sleep(300);
        } catch (InterruptedException e) {
            Thread.currentThread().interrupt();
        }
        DONE.countDown();
    }

    // Average time between starts 2 to 5, to the nearest 100 ms. The first run is left out
    // because it can start late while the context is still starting.
    static long averageGap(List<Long> starts) {
        long ms = TimeUnit.NANOSECONDS.toMillis(starts.get(4) - starts.get(1)) / 3;
        return Math.round(ms / 100.0) * 100;
    }

    @Configuration
    @EnableScheduling
    static class Config {
        @Bean
        ThreadPoolTaskScheduler taskScheduler() {
            ThreadPoolTaskScheduler scheduler = new ThreadPoolTaskScheduler();
            scheduler.setPoolSize(2);
            return scheduler;
        }

        @Bean
        Jobs jobs() {
            return new Jobs();
        }
    }

    static class Jobs {
        final List<Long> rateStarts = new CopyOnWriteArrayList<>();
        final List<Long> delayStarts = new CopyOnWriteArrayList<>();

        @Scheduled(fixedRate = 500)
        void everyHalfSecondFromStart() {
            work(rateStarts);
        }

        @Scheduled(fixedDelay = 500)
        void halfSecondAfterEachEnd() {
            work(delayStarts);
        }
    }

    public static void main(String[] args) throws InterruptedException {
        try (var context = new AnnotationConfigApplicationContext(Config.class)) {
            DONE.await(10, TimeUnit.SECONDS);
            Jobs jobs = context.getBean(Jobs.class);
            System.out.println("Each run takes 300 ms. Average time from one start to the next:");
            System.out.println("fixedRate  = 500: " + averageGap(jobs.rateStarts) + " ms");
            System.out.println("fixedDelay = 500: " + averageGap(jobs.delayStarts) + " ms");
        }
    }
}
Output
Each run takes 300 ms. Average time from one start to the next:
fixedRate  = 500: 500 ms
fixedDelay = 500: 800 ms
  • fixedRate = 500 started a run every 500 ms on average. The 300 ms of work fits inside the interval, so the starts kept a steady pace.
  • fixedDelay = 500 waited 500 ms after each run ended, so the starts were 800 ms apart: 300 ms of work plus 500 ms of delay.
  • The program averages the gaps after the first run, because the first run can start late while the context is still starting up.

With ThreadPoolTaskScheduler, a fixedRate task that takes longer than its rate does not start a second run in parallel. The next run waits until the current one finishes and then starts at once, so a task that is always too slow runs back to back. That rule depends on the scheduler, as the next section shows. A fixedDelay task always leaves its delay between runs, which makes it the safer choice for polling. Both accept an initialDelay, and both have string forms such as fixedDelayString = "${poll.interval}" for values taken from configuration.

One thread for every task by default

A heartbeat every 200 ms and a nightly export that takes one second look unrelated. This program runs them together, first with no scheduler bean and then with a pool of 4 threads, and measures the longest gap between heartbeats:

Java
import java.util.ArrayList;
import java.util.List;
import java.util.Set;
import java.util.TreeSet;
import java.util.concurrent.TimeUnit;
import java.util.logging.Level;
import java.util.logging.Logger;
import org.springframework.context.annotation.AnnotationConfigApplicationContext;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.scheduling.annotation.EnableScheduling;
import org.springframework.scheduling.annotation.Scheduled;
import org.springframework.scheduling.concurrent.ThreadPoolTaskScheduler;

public class SchedulerThreads {

    @Configuration
    @EnableScheduling
    static class DefaultConfig {
        @Bean
        Jobs jobs() {
            return new Jobs();
        }
    }

    @Configuration
    @EnableScheduling
    static class PoolConfig {
        @Bean
        ThreadPoolTaskScheduler taskScheduler() {
            ThreadPoolTaskScheduler scheduler = new ThreadPoolTaskScheduler();
            scheduler.setPoolSize(4);
            scheduler.setThreadNamePrefix("sched-");
            return scheduler;
        }

        @Bean
        Jobs jobs() {
            return new Jobs();
        }
    }

    static class Jobs {
        private final long start = System.nanoTime();
        private final List<Long> heartbeats = new ArrayList<>();
        private final Set<String> threads = new TreeSet<>();

        // pool threads are numbered in the order they start, which varies between runs
        static String threadName() {
            String name = Thread.currentThread().getName();
            return name.startsWith("sched-") ? "sched-N" : name;
        }

        synchronized void record(String thread) {
            threads.add(thread);
        }

        @Scheduled(fixedRate = 200)
        void heartbeat() {
            record("heartbeat on " + threadName());
            synchronized (this) {
                heartbeats.add(TimeUnit.NANOSECONDS.toMillis(System.nanoTime() - start));
            }
        }

        @Scheduled(initialDelay = 300, fixedDelay = 60000)
        void nightlyExport() throws InterruptedException {
            record("export    on " + threadName());
            Thread.sleep(1000);
        }

        synchronized long longestGapMs() {
            long longest = 0;
            for (int i = 1; i < heartbeats.size(); i++) {
                longest = Math.max(longest, heartbeats.get(i) - heartbeats.get(i - 1));
            }
            return longest;
        }

        synchronized Set<String> threads() {
            return threads;
        }
    }

    static void run(String label, Class<?> config) throws InterruptedException {
        try (var context = new AnnotationConfigApplicationContext(config)) {
            Thread.sleep(1600);
            Jobs jobs = context.getBean(Jobs.class);
            System.out.println(label);
            jobs.threads().forEach(t -> System.out.println("  " + t));
            System.out.println("  heartbeat paused for over 500 ms: "
                    + (jobs.longestGapMs() > 500));
        }
    }

    public static void main(String[] args) throws InterruptedException {
        Logger.getLogger("org.springframework").setLevel(Level.WARNING);
        run("No TaskScheduler bean:", DefaultConfig.class);
        run("ThreadPoolTaskScheduler with 4 threads:", PoolConfig.class);
    }
}
Output
No TaskScheduler bean:
  export    on pool-1-thread-1
  heartbeat on pool-1-thread-1
  heartbeat paused for over 500 ms: true
ThreadPoolTaskScheduler with 4 threads:
  export    on sched-N
  heartbeat on sched-N
  heartbeat paused for over 500 ms: false
  • Without a TaskScheduler bean, both tasks ran on pool-1-thread-1, the single thread Spring created. Spring logs "No TaskScheduler/ScheduledExecutorService bean found for scheduled processing" at INFO level when it does this; the program turns that log off to keep the output stable.
  • While the export ran, the heartbeat could not, so it paused for over 500 ms. In a typical run the longest gap was about 1100 ms instead of 200 ms: the 1 second export plus one interval. A health check built on that heartbeat would have reported the application as stuck.
  • With a ThreadPoolTaskScheduler of 4 threads named sched-, the export and the heartbeat ran on separate threads, and the heartbeat never paused. The program prints sched-N because the thread numbers change between runs.

Spring Boot auto-configures a ThreadPoolTaskScheduler with one thread as well, so the same problem appears there. Raise it with spring.task.scheduling.pool.size. With spring.threads.virtual.enabled=true on Java 21 or later, Boot uses a SimpleAsyncTaskScheduler instead, which starts a new virtual thread for each run and ignores the pool size. Its reference documentation recommends fixed rates and cron triggers with it, because all fixed-delay tasks run on its single scheduler thread.

A new thread for each run also changes the overlap rule from the previous section. This program runs a 300 ms task at a fixed rate of 200 ms on both schedulers:

Java
import java.util.concurrent.atomic.AtomicInteger;
import java.util.logging.Level;
import java.util.logging.Logger;
import org.springframework.context.annotation.AnnotationConfigApplicationContext;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.scheduling.annotation.EnableScheduling;
import org.springframework.scheduling.annotation.Scheduled;
import org.springframework.scheduling.concurrent.SimpleAsyncTaskScheduler;
import org.springframework.scheduling.concurrent.ThreadPoolTaskScheduler;

public class RateOverlap {

    @Configuration
    @EnableScheduling
    static class PoolConfig {
        @Bean
        ThreadPoolTaskScheduler taskScheduler() {
            ThreadPoolTaskScheduler scheduler = new ThreadPoolTaskScheduler();
            scheduler.setPoolSize(4);
            return scheduler;
        }

        @Bean
        SlowJob slowJob() {
            return new SlowJob();
        }
    }

    @Configuration
    @EnableScheduling
    static class VirtualConfig {
        @Bean
        SimpleAsyncTaskScheduler taskScheduler() {
            SimpleAsyncTaskScheduler scheduler = new SimpleAsyncTaskScheduler();
            scheduler.setVirtualThreads(true);
            return scheduler;
        }

        @Bean
        SlowJob slowJob() {
            return new SlowJob();
        }
    }

    static class SlowJob {
        private final AtomicInteger running = new AtomicInteger();
        private final AtomicInteger mostAtOnce = new AtomicInteger();

        @Scheduled(fixedRate = 200)
        void export() throws InterruptedException {
            mostAtOnce.accumulateAndGet(running.incrementAndGet(), Math::max);
            Thread.sleep(300);
            running.decrementAndGet();
        }
    }

    static void run(String label, Class<?> config) throws InterruptedException {
        var context = new AnnotationConfigApplicationContext(config);
        Thread.sleep(1500);
        SlowJob job = context.getBean(SlowJob.class);
        boolean overlapped = job.mostAtOnce.get() > 1;
        context.close();
        System.out.println(label + ": runs overlapped = " + overlapped);
    }

    public static void main(String[] args) throws InterruptedException {
        Logger.getLogger("org.springframework").setLevel(Level.WARNING);
        System.out.println("fixedRate = 200 ms, each run takes 300 ms");
        run("ThreadPoolTaskScheduler, 4 threads", PoolConfig.class);
        run("SimpleAsyncTaskScheduler, virtual  ", VirtualConfig.class);
    }
}
Output
fixedRate = 200 ms, each run takes 300 ms
ThreadPoolTaskScheduler, 4 threads: runs overlapped = false
SimpleAsyncTaskScheduler, virtual  : runs overlapped = true
  • ThreadPoolTaskScheduler never ran the task twice at once, even with idle threads in its pool. It delayed each run until the previous one had finished.
  • SimpleAsyncTaskScheduler started each run on time on a new virtual thread, so runs of the same task overlapped: a run started every 200 ms while each one lasted 300 ms. A job that is not safe to run concurrently, such as one that reads and then updates the same rows, needs fixedDelay or its own lock on this scheduler.

Cron expressions

Spring's cron expressions have six fields, not the five of Unix cron: second, minute, hour, day of month, month, day of week. CronExpression.parse, available since Spring Framework 5.3, computes the next matching time for any start time, so expressions can be checked without waiting for them. Each one here starts from Saturday 14 November 2026, 09:07:30:

Java
import java.time.LocalDateTime;
import java.time.ZoneId;
import java.time.ZonedDateTime;
import java.time.format.DateTimeFormatter;
import java.util.Locale;
import org.springframework.scheduling.support.CronExpression;

public class CronNext {

    static final DateTimeFormatter FORMAT = DateTimeFormatter.ofPattern("EEE yyyy-MM-dd HH:mm:ss",
            Locale.ENGLISH);

    static void show(String cron, String meaning, LocalDateTime from) {
        CronExpression expression = CronExpression.parse(cron);
        LocalDateTime first = expression.next(from);
        LocalDateTime second = expression.next(first);
        System.out.printf("%-22s %-34s %s, %s%n", cron, meaning,
                FORMAT.format(first), FORMAT.format(second));
    }

    public static void main(String[] args) {
        LocalDateTime from = LocalDateTime.of(2026, 11, 14, 9, 7, 30);
        System.out.println("Starting from " + FORMAT.format(from) + ", the next two runs:");
        show("0 */15 * * * *", "every 15 minutes", from);
        show("0 0 9-17 * * MON-FRI", "on the hour, office hours", from);
        show("0 30 2 * * *", "every day at 02:30", from);
        show("@weekly", "macro: Sunday midnight", from);
        show("0 0 18 L * *", "last day of the month", from);
        show("0 0 9 LW * *", "last weekday of the month", from);
        show("0 0 9 1W * *", "first weekday of the month", from);
        show("0 0 10 * * MON#2", "second Monday of the month", from);
        show("0 0 10 * * FRIL", "last Friday of the month", from);

        System.out.println();
        System.out.println("Daylight saving time in Europe/London, \"0 30 1 * * *\":");
        CronExpression daily = CronExpression.parse("0 30 1 * * *");
        ZoneId london = ZoneId.of("Europe/London");
        ZonedDateTime springForward = ZonedDateTime.of(2026, 3, 28, 12, 0, 0, 0, london);
        ZonedDateTime fallBack = ZonedDateTime.of(2026, 10, 24, 12, 0, 0, 0, london);
        for (ZonedDateTime start : new ZonedDateTime[] {springForward, fallBack}) {
            ZonedDateTime t = start;
            for (int i = 0; i < 3; i++) {
                t = daily.next(t);
                System.out.println("  " + t);
            }
        }

        System.out.println();
        for (String bad : new String[] {"0 0 9 * *", "0 0 25 * * *"}) {
            try {
                CronExpression.parse(bad);
            } catch (IllegalArgumentException e) {
                System.out.println("\"" + bad + "\" rejected: " + e.getMessage());
            }
        }
    }
}
Output
Starting from Sat 2026-11-14 09:07:30, the next two runs:
0 */15 * * * *         every 15 minutes                   Sat 2026-11-14 09:15:00, Sat 2026-11-14 09:30:00
0 0 9-17 * * MON-FRI   on the hour, office hours          Mon 2026-11-16 09:00:00, Mon 2026-11-16 10:00:00
0 30 2 * * *           every day at 02:30                 Sun 2026-11-15 02:30:00, Mon 2026-11-16 02:30:00
@weekly                macro: Sunday midnight             Sun 2026-11-15 00:00:00, Sun 2026-11-22 00:00:00
0 0 18 L * *           last day of the month              Mon 2026-11-30 18:00:00, Thu 2026-12-31 18:00:00
0 0 9 LW * *           last weekday of the month          Mon 2026-11-30 09:00:00, Thu 2026-12-31 09:00:00
0 0 9 1W * *           first weekday of the month         Tue 2026-12-01 09:00:00, Fri 2027-01-01 09:00:00
0 0 10 * * MON#2       second Monday of the month         Mon 2026-12-14 10:00:00, Mon 2027-01-11 10:00:00
0 0 10 * * FRIL        last Friday of the month           Fri 2026-11-27 10:00:00, Fri 2026-12-25 10:00:00

Daylight saving time in Europe/London, "0 30 1 * * *":
  2026-03-30T01:30+01:00[Europe/London]
  2026-03-31T01:30+01:00[Europe/London]
  2026-04-01T01:30+01:00[Europe/London]
  2026-10-25T01:30+01:00[Europe/London]
  2026-10-25T01:30Z[Europe/London]
  2026-10-26T01:30Z[Europe/London]

"0 0 9 * *" rejected: Cron expression must consist of 6 fields (found 5 in "0 0 9 * *")
"0 0 25 * * *" rejected: Invalid value for HourOfDay (valid values 0 - 23): 25 '25' in cron expression "0 0 25 * * *"
  • 0 0 9-17 * * MON-FRI skipped the weekend: from a Saturday morning the next run is Monday at 09:00.
  • @weekly is a macro for 0 0 0 * * 0, Sunday at midnight. The others are @yearly, @monthly, @daily and @hourly.
  • L in the day-of-month field is the last day, 30 November and then 31 December. LW is the last weekday, and 1W the weekday nearest the 1st: 1 January 2027 is a Friday, so it ran then.
  • MON#2 is the second Monday of the month, and FRIL the last Friday.
  • Daylight saving time changes the schedule. On 29 March 2026 London clocks jump from 01:00 to 02:00, so 01:30 did not exist and that day had no run at all. On 25 October 01:30 happened twice, once in summer time (+01:00) and once in winter time (Z), and the job ran twice.
  • A five-field Unix expression was rejected with "must consist of 6 fields", and hour 25 with a message naming the field. Spring checks expressions when the context starts, so a typo fails at startup rather than at 02:00.

Use zone = "Europe/London" or another zone ID on @Scheduled to fix the time zone; without it, the scheduler's default zone is used. To avoid the daylight saving problems, schedule nightly jobs outside 01:00 to 03:00, or run them in UTC.

A failing task keeps its schedule

Scheduled jobs often call systems that fail now and then. What happens to the schedule after an exception depends on who runs the task. This program throws on run 2, first in a Spring @Scheduled method and then in a plain JDK ScheduledExecutorService:

Java
import java.util.concurrent.CountDownLatch;
import java.util.concurrent.Executors;
import java.util.concurrent.ScheduledExecutorService;
import java.util.concurrent.ScheduledFuture;
import java.util.concurrent.TimeUnit;
import java.util.concurrent.atomic.AtomicInteger;
import org.springframework.context.annotation.AnnotationConfigApplicationContext;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.scheduling.annotation.EnableScheduling;
import org.springframework.scheduling.annotation.Scheduled;
import org.springframework.scheduling.concurrent.ThreadPoolTaskScheduler;

public class FailingTasks {

    static final CountDownLatch FOUR_RUNS = new CountDownLatch(4);

    @Configuration
    @EnableScheduling
    static class Config {
        @Bean
        ThreadPoolTaskScheduler taskScheduler() {
            ThreadPoolTaskScheduler scheduler = new ThreadPoolTaskScheduler();
            scheduler.setErrorHandler(error ->
                    System.out.println("    ErrorHandler: " + error.getMessage()));
            return scheduler;
        }

        @Bean
        SyncJob syncJob() {
            return new SyncJob();
        }
    }

    static class SyncJob {
        private final AtomicInteger runs = new AtomicInteger();

        @Scheduled(fixedRate = 100)
        void sync() {
            int run = runs.incrementAndGet();
            if (run > 4) {
                return;
            }
            System.out.println("  run " + run);
            FOUR_RUNS.countDown();
            if (run == 2) {
                throw new IllegalStateException("partner API returned 503");
            }
        }
    }

    public static void main(String[] args) throws Exception {
        System.out.println("Spring @Scheduled task that fails on run 2:");
        var context = new AnnotationConfigApplicationContext(Config.class);
        FOUR_RUNS.await(5, TimeUnit.SECONDS);
        context.close();

        System.out.println("Plain ScheduledExecutorService task that fails on run 2:");
        AtomicInteger runs = new AtomicInteger();
        ScheduledExecutorService executor = Executors.newSingleThreadScheduledExecutor();
        ScheduledFuture<?> future = executor.scheduleAtFixedRate(() -> {
            int run = runs.incrementAndGet();
            System.out.println("  run " + run);
            if (run == 2) {
                throw new IllegalStateException("partner API returned 503");
            }
        }, 0, 100, TimeUnit.MILLISECONDS);
        Thread.sleep(600);
        System.out.println("  after 600 ms: runs = " + runs.get()
                + ", future done = " + future.isDone());
        executor.shutdown();
    }
}
Output
Spring @Scheduled task that fails on run 2:
  run 1
  run 2
    ErrorHandler: partner API returned 503
  run 3
  run 4
Plain ScheduledExecutorService task that fails on run 2:
  run 1
  run 2
  after 600 ms: runs = 2, future done = true
  • Spring passed the exception from run 2 to the scheduler's ErrorHandler, and runs 3 and 4 followed as planned. Without a custom handler, Spring logs the exception and the task carries on.
  • The JDK executor stopped the task after the exception. Six intervals later there had still been only 2 runs, and the future was done. Nothing was logged; the exception is only visible through future.get().

Spring keeping the schedule is usually what you want, but it can hide a job that fails every time. Count failures in the ErrorHandler or in the task itself and send them to your metrics, so a job that has not succeeded for a day raises an alert.

Schedules decided at run time

Annotations fix the schedule at startup. When the next run depends on what the last one found, schedule the task through TaskScheduler with your own Trigger. A queue poller is the common case: poll quickly while there is work, and back off when the queue is empty:

Java
import java.time.Duration;
import java.time.Instant;
import java.util.ArrayList;
import java.util.List;
import java.util.concurrent.CountDownLatch;
import java.util.concurrent.ScheduledFuture;
import java.util.concurrent.TimeUnit;
import java.util.concurrent.atomic.AtomicInteger;
import org.springframework.scheduling.Trigger;
import org.springframework.scheduling.concurrent.ThreadPoolTaskScheduler;

public class DynamicTrigger {

    public static void main(String[] args) throws InterruptedException {
        ThreadPoolTaskScheduler scheduler = new ThreadPoolTaskScheduler();
        scheduler.setThreadNamePrefix("poller-");
        scheduler.initialize();

        // Poll a queue: wait 100 ms after a run that found work, and double the wait
        // (up to 800 ms) after each run that found nothing.
        int[] queueSizes = {3, 1, 0, 0, 0, 0, 2, 0};
        AtomicInteger run = new AtomicInteger();
        List<String> log = new ArrayList<>();
        List<Long> waits = new ArrayList<>();
        long[] wait = {100};
        CountDownLatch done = new CountDownLatch(queueSizes.length);

        Runnable poll = () -> {
            int found = queueSizes[run.getAndIncrement()];
            wait[0] = found > 0 ? 100 : Math.min(wait[0] * 2, 800);
            waits.add(wait[0]);
            log.add("found " + found + ", next poll in " + wait[0] + " ms");
            done.countDown();
        };
        Trigger backoff = context -> {
            Instant last = context.lastCompletion();
            return last == null ? context.getClock().instant() : last.plusMillis(wait[0]);
        };

        ScheduledFuture<?> future = scheduler.schedule(poll, backoff);
        done.await(10, TimeUnit.SECONDS);
        future.cancel(false);

        Duration waited = Duration.ZERO;
        for (int i = 0; i < log.size(); i++) {
            System.out.println("poll " + (i + 1) + ": " + log.get(i));
        }
        for (int i = 0; i < waits.size() - 1; i++) {
            waited = waited.plusMillis(waits.get(i));
        }
        System.out.println("waits between the 8 polls: " + waited.toMillis()
                + " ms; a fixed 100 ms delay would poll "
                + (waited.toMillis() / 100 + 1) + " times in that time");
        System.out.println("cancelled = " + future.isCancelled());
        scheduler.shutdown();
    }
}
Output
poll 1: found 3, next poll in 100 ms
poll 2: found 1, next poll in 100 ms
poll 3: found 0, next poll in 200 ms
poll 4: found 0, next poll in 400 ms
poll 5: found 0, next poll in 800 ms
poll 6: found 0, next poll in 800 ms
poll 7: found 2, next poll in 100 ms
poll 8: found 0, next poll in 200 ms
waits between the 8 polls: 2500 ms; a fixed 100 ms delay would poll 26 times in that time
cancelled = true
  • The trigger is a lambda that returns the next run time from TriggerContext. It takes the end of the last run, lastCompletion(), and adds the current wait.
  • Polls 1 and 2 found work, so the wait stayed at 100 ms. Each empty poll doubled it to 200, 400 and then 800 ms, the limit. Poll 7 found 2 items and dropped the wait back to 100 ms.
  • The waits between the 8 polls added up to 2500 ms. A fixed 100 ms delay would have polled 26 times in that period, mostly finding nothing.
  • schedule returned a ScheduledFuture, and cancel(false) stopped the task without interrupting a run in progress.

For a dynamic schedule on a bean, implement SchedulingConfigurer and register the task in configureTasks; it then shares the scheduler of the @Scheduled methods. PeriodicTrigger and CronTrigger are the built-in triggers behind fixed and cron schedules.

Several instances run every job

A scheduled method runs in every JVM that contains the bean. Once the application runs as 2 or more instances, for availability or scale, every instance sends the 02:00 invoices. This program starts two application contexts against one shared H2 database to stand in for two instances, and each runs the invoice job for three "days":

Java
import java.util.concurrent.CountDownLatch;
import java.util.concurrent.TimeUnit;
import java.util.logging.Level;
import java.util.logging.Logger;
import javax.sql.DataSource;
import org.springframework.context.annotation.AnnotationConfigApplicationContext;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.dao.DuplicateKeyException;
import org.springframework.jdbc.core.JdbcTemplate;
import org.springframework.jdbc.datasource.DriverManagerDataSource;
import org.springframework.scheduling.annotation.EnableScheduling;
import org.springframework.scheduling.annotation.Scheduled;

public class MultiInstance {

    static final String URL = "jdbc:h2:mem:shared;DB_CLOSE_DELAY=-1";
    static final CountDownLatch ALL_RUNS = new CountDownLatch(6);

    @Configuration
    @EnableScheduling
    static class Config {
        @Bean
        JdbcTemplate jdbc() {
            DataSource dataSource = new DriverManagerDataSource(URL);
            return new JdbcTemplate(dataSource);
        }

        @Bean
        InvoiceJob invoiceJob(JdbcTemplate jdbc, String instance) {
            return new InvoiceJob(jdbc, instance);
        }
    }

    static class InvoiceJob {
        private final JdbcTemplate jdbc;
        private final String instance;
        private int day;

        InvoiceJob(JdbcTemplate jdbc, String instance) {
            this.jdbc = jdbc;
            this.instance = instance;
        }

        // Stands in for cron = "0 0 2 * * *": each run is one "day".
        @Scheduled(fixedRate = 200)
        void sendInvoices() {
            if (day == 3) {
                return;
            }
            day++;
            jdbc.update("INSERT INTO invoices_unguarded VALUES (?, ?)", day, instance);
            try {
                jdbc.update("INSERT INTO job_runs VALUES ('invoices', ?, ?)", day, instance);
                jdbc.update("INSERT INTO invoices_guarded VALUES (?, ?)", day, instance);
            } catch (DuplicateKeyException e) {
                // the other instance already claimed this day
            }
            ALL_RUNS.countDown();
        }
    }

    static AnnotationConfigApplicationContext start(String instance) {
        var context = new AnnotationConfigApplicationContext();
        context.registerBean("instance", String.class, () -> instance);
        context.register(Config.class);
        context.refresh();
        return context;
    }

    public static void main(String[] args) throws InterruptedException {
        Logger.getLogger("org.springframework").setLevel(Level.WARNING);
        JdbcTemplate setup = new JdbcTemplate(new DriverManagerDataSource(URL));
        setup.execute("CREATE TABLE invoices_unguarded (run_day INT, sent_by VARCHAR(10))");
        setup.execute("CREATE TABLE invoices_guarded (run_day INT, sent_by VARCHAR(10))");
        setup.execute("CREATE TABLE job_runs (job VARCHAR(20), run_day INT, claimed_by VARCHAR(10),"
                + " PRIMARY KEY (job, run_day))");

        var a = start("A");
        var b = start("B");
        ALL_RUNS.await(5, TimeUnit.SECONDS);
        a.close();
        b.close();

        System.out.println("Two instances, each running the job for days 1 to 3.");
        System.out.println("Without a lock, invoice batches sent per day:");
        setup.queryForList("SELECT run_day, COUNT(*) n FROM invoices_unguarded GROUP BY run_day"
                + " ORDER BY run_day").forEach(r -> System.out.println("  day " + r.get("RUN_DAY")
                + ": " + r.get("N")));
        System.out.println("With a claim row per day in job_runs:");
        setup.queryForList("SELECT run_day, COUNT(*) n FROM invoices_guarded GROUP BY run_day"
                + " ORDER BY run_day").forEach(r -> System.out.println("  day " + r.get("RUN_DAY")
                + ": " + r.get("N")));
    }
}
Output
Two instances, each running the job for days 1 to 3.
Without a lock, invoice batches sent per day:
  day 1: 2
  day 2: 2
  day 3: 2
With a claim row per day in job_runs:
  day 1: 1
  day 2: 1
  day 3: 1
  • Without a lock, both instances sent invoices for every day: 2 batches each for days 1, 2 and 3. Customers would have been billed twice.
  • With a claim row, each instance first inserted ('invoices', day) into job_runs, whose primary key covers job and day. The second insert for the same day failed with DuplicateKeyException, so only one batch was sent per day. Which instance won each day varies between runs.

The claim row works because the database decides between the instances, and it also records which instance ran each day. Libraries do the same job for real systems. ShedLock adds a @SchedulerLock annotation that holds a lock row with an expiry time, so a crashed instance does not keep the lock forever. Quartz with its JDBC job store runs each job on one node of a cluster and can catch up on missed runs. Neither was run here. For jobs that process large data sets in chunks, with restart after failure, see Spring Batch.

Shutdown and long-running tasks

When the application context closes, Spring cancels all scheduled tasks, so no new runs start. A run already in progress is a different matter:

  • Interrupts: ThreadPoolTaskScheduler shuts its executor down when the context closes. A task that ignores interrupts can keep the JVM waiting, and one that is interrupted in the middle of a batch may leave partial work behind.
  • Waiting for runs to finish: setWaitForTasksToCompleteOnShutdown(true) and setAwaitTerminationSeconds(30) on ThreadPoolTaskScheduler let a running task finish within a limit. In Spring Boot, the matching properties are spring.task.scheduling.shutdown.await-termination and spring.task.scheduling.shutdown.await-termination-period.
  • Idempotent work: design each run so that repeating it is safe, for example by recording which records it has processed. A run cut short by a deployment can then simply be repeated. The idempotency page covers the techniques.

Since Spring Framework 6.1, ThreadPoolTaskScheduler also takes part in Spring's lifecycle, so it can be paused and resumed with the context's stop() and start(), and it shuts down gracefully.

Choosing a schedule and a scheduler

Common scheduling situations and what fits them
SituationUse
Poll or clean up, never piling runs on top of each otherfixedDelay
Keep a steady pace, such as a heartbeatfixedRate, with a body much shorter than the rate
A calendar time, such as 02:00 every daycron with an explicit zone
Values that differ per environmentfixedDelayString or cron with a ${...} placeholder
More than one task, or any slow taskA ThreadPoolTaskScheduler with enough threads, or spring.task.scheduling.pool.size
Java 21 or later with virtual threadsSimpleAsyncTaskScheduler, with fixed rates or cron
A schedule that changes at run timeTaskScheduler with a custom Trigger
Several instances, a job that must run onceA lock in the database, such as ShedLock, or Quartz in cluster mode
Large batch jobs with restartSpring Batch, started by a scheduler

Four rules explain most scheduling bugs: all tasks share one thread unless you configure more, a slow run delays the next one instead of overlapping it, cron jobs between 01:00 and 03:00 can be skipped or doubled by daylight saving time, and every instance of the application runs every job. Related pages: Spring @Async for running work on executor threads, and Spring Batch.