Skip to content
Tutorials Center
My learning

Topics

Lesson 48 of 66 ยท Production Features

Scheduling and Asynchronous Work

Run jobs on a schedule with @Scheduled and cron, move slow work off the request thread with @Async, tune executors, use virtual threads and shut down gracefully.

Not everything an application does should happen inside a web request. A nightly cleanup, a report that takes ten seconds, a welcome email, a cache refresh every minute: these belong on a schedule or on a background thread. Spring Boot supports both with two annotations, @Scheduled and @Async, running on executors that Boot configures for you.

This lesson explains how each annotation works, the single-thread default that surprises people, how to size and bound executors, what changes when you turn on virtual threads, and how to stop background work cleanly during a deployment. The real Spring code is read-only; the TryIts model the mechanisms with plain Java so you can see the timing and queue behavior yourself.

Work that leaves the request thread

@Scheduled Runs by itself, on a clock.
@Async Runs when called, but on another thread.
Executors The thread pools that run both.

Both are proxy-based, just like @Transactional and @Cacheable.

1 / 2

Scheduled jobs

Turn scheduling on once with @EnableScheduling (on any configuration class, often the main class), then annotate a no-argument method of a bean:

Java
import org.springframework.scheduling.annotation.EnableScheduling;
import org.springframework.scheduling.annotation.Scheduled;
import org.springframework.stereotype.Component;

@Configuration
@EnableScheduling
class SchedulingConfig {}

@Component
class Housekeeping {

    @Scheduled(fixedRate = 60_000)                       // every minute, measured start to start
    void refreshRates() { ... }

    @Scheduled(fixedDelay = 30_000, initialDelay = 10_000) // 30 s AFTER the previous run ends
    void pollInbox() { ... }

    @Scheduled(cron = "0 0 2 * * *", zone = "Europe/Berlin") // every day at 02:00 Berlin time
    void purgeOldSessions() { ... }
}

The three styles:

  • fixedRate starts a run every N milliseconds, whatever the previous run did. If a run takes longer than the interval, the next one waits for it (by default runs of one method never overlap in the same scheduler).
  • fixedDelay waits N milliseconds after the previous run finished. Use it for polling, where you do not want runs to pile up.
  • cron uses a calendar expression. Spring's cron has six fields, with seconds first: second minute hour day-of-month month day-of-week. A classic five-field Unix expression will not do what you expect. Always pass a zone, because without it the server's time zone decides, and a server moved between regions changes when your job runs.

Durations also accept strings and property placeholders, which lets you configure schedules per environment (@Scheduled(fixedRateString = "${jobs.rates.interval:PT1M}"), ISO-8601 PT1M meaning one minute). A few cron examples:

Expression Meaning
0 */15 * * * * every 15 minutes, on the minute
0 0 9 * * MON-FRI 09:00 on weekdays
0 0 0 1 * * midnight on the first of each month
*/10 * * * * * every 10 seconds

The single-thread default

Boot configures a scheduler with a pool of one thread (spring.task.scheduling.pool.size=1). All @Scheduled methods in the application share it. If purgeOldSessions takes ten minutes, refreshRates does not run for ten minutes. Two remedies: make the jobs fast (hand heavy work to an executor), or enlarge the pool:

PROPERTIES
spring.task.scheduling.pool.size=4
spring.task.scheduling.thread-name-prefix=sched-

Scheduled methods take no arguments and their return value is ignored. An exception thrown from a run is logged and the schedule continues (for fixedRate, fixedDelay and cron), so a failing job does not kill itself, but it can fail silently forever if nobody reads the logs. Catch exceptions, count failures with a metric (see Observability) and alert on them.

Many instances, one job

@Scheduled knows nothing about other copies of your application. If you run three instances behind a load balancer, all three run the nightly job, and customers get three emails. Solutions are a distributed lock (ShedLock is a popular library that uses a database table or Redis), a single dedicated "scheduler" instance, or an external trigger such as a Kubernetes CronJob. Which one is right depends on whether the job must run exactly once or merely at least once; design jobs to be idempotent (safe to run twice) either way.

How the schedules differ, shown in virtual time

Real clocks make a poor demo, so the first TryIt simulates time: a "task" takes 4 seconds, and we compute when each style would start it over one minute. The numbers come from the rules above, not from sleeping. What is real: the scheduling rules. What is the stand-in: no threads, no real clock, and no overlap handling beyond waiting for the previous run.

Java fixedRate vs fixedDelay in virtual time

Press Run (or Ctrl + Enter) to see the result here.

Program input ยท what you'd type while the program runs

Type the answers before you press Run, one per line. Each time the program reads a line (with IO.readln() or a Scanner), it gets the next line from this box.

The last line is the lesson of fixedRate: when a job is slower than its interval it runs back-to-back, and the job effectively never rests. If that matters, switch to fixedDelay or shorten the work.

Asynchronous methods with @Async

@Async makes a method return immediately while its body runs on another thread. Enable it with @EnableAsync, then annotate:

Java
@Service
class WelcomeService {

    @Async
    void sendWelcomeEmail(String address) {
        // runs on an executor thread; the caller does not wait
    }

    @Async
    CompletableFuture<Report> buildReport(long accountId) {
        Report r = slowReportQuery(accountId);
        return CompletableFuture.completedFuture(r);
    }
}

The return type must be void, Future or CompletableFuture. Callers who need the result use the future; callers who do not simply ignore it. Rules that follow from how @Async works:

  • It is proxy-based. Calling this.sendWelcomeEmail(...) from another method of the same class is a plain method call and runs synchronously, the same self-invocation pitfall you meet with @Transactional (Transactions). Call it from a different bean.
  • The caller's context does not follow. The new thread has no transaction, no security context and no MDC unless you set up propagation. Pass what you need as arguments (ids, not entities with lazy fields).
  • Exceptions vanish into a handler. A void method that throws cannot report to its caller. Spring logs it through an AsyncUncaughtExceptionHandler; return a CompletableFuture when the caller must observe failure.
  • Not durable. If the application stops with work in the queue, that work is gone. For anything that must survive a crash, use a message broker (Messaging).

The executor behind it

Boot creates a ThreadPoolTaskExecutor bean named applicationTaskExecutor and @Async uses it. Its settings:

PROPERTIES
spring.task.execution.pool.core-size=8
spring.task.execution.pool.max-size=16
spring.task.execution.pool.queue-capacity=100
spring.task.execution.thread-name-prefix=app-async-

Understanding when a pool starts more threads is worth a minute, because the default catches people out. A ThreadPoolExecutor first uses up to core-size threads. After that it puts tasks in the queue, and it only creates extra threads up to max-size when the queue is full. Boot's default queue capacity is unbounded, so the queue is never full and max-size has no effect: you have exactly core-size threads and a queue that can grow until memory runs out. The two safe patterns are a bounded queue (so overload is rejected visibly) or a deliberate core size equal to the concurrency you want.

When the queue and threads are all full, a rejection policy decides what happens: throw RejectedExecutionException (the default), run the task on the caller's thread ("caller runs", which slows producers down, a simple form of back-pressure), or drop it. Choosing is a business decision: dropping an analytics event is fine; dropping a payment is not.

Java Core, queue and max threads in a pool

Press Run (or Ctrl + Enter) to see the result here.

Program input ยท what you'd type while the program runs

Type the answers before you press Run, one per line. Each time the program reads a line (with IO.readln() or a Scanner), it gets the next line from this box.

This one is not a stand-in: it is the real ThreadPoolExecutor that Spring's ThreadPoolTaskExecutor wraps. Read the output as a story: two core threads start, the next two tasks wait in the queue, tasks five and six force new threads up to the maximum of four, and the seventh is rejected.

Virtual threads

Platform threads are expensive (roughly a megabyte of stack each, and the operating system schedules them), so pools keep them few and queue the rest. Virtual threads (final in Java 21) are cheap threads managed by the JVM: you can have hundreds of thousands, and when one blocks on I/O (a database call, an HTTP request) it releases its carrier thread instead of holding it. With virtual threads you stop pooling and write plain blocking code for each task.

Boot (3.2 and later, on Java 21+) switches everything over with one property:

PROPERTIES
spring.threads.virtual.enabled=true

This makes the embedded web server handle each request on a virtual thread, makes @Async and other application task executors use virtual threads (one new thread per task, no pool sizes to tune), and makes the scheduler run each scheduled job on a virtual thread so slow jobs no longer block each other. It is a good fit for I/O-bound workloads: lots of waiting on databases and other services. It does not speed up CPU-bound work, and it does not fix a slow database: you can now create ten thousand concurrent queries, which will overwhelm a connection pool of ten. Keep limits (pool sizes, semaphores, rate limits) on the resources that are actually scarce. Pinning (a virtual thread stuck to its carrier inside a synchronized block that blocks) was a limitation of Java 21 that Java 24+ largely removes, which is another reason to run a recent JDK. More on the cost side in Performance Tuning.

The next TryIt compares a pool of four platform threads with virtual threads on 40 tasks that each wait 50 ms (a stand-in for a blocking call). Timings differ per machine, so the program prints only comparisons that hold everywhere: a four-thread pool needs at least ten rounds of 50 ms, while 40 virtual threads overlap their waiting.

Java Blocked tasks: pool of 4 vs virtual threads

Press Run (or Ctrl + Enter) to see the result here.

Program input ยท what you'd type while the program runs

Type the answers before you press Run, one per line. Each time the program reads a line (with IO.readln() or a Scanner), it gets the next line from this box.

The comparison is real Java; the sleeping tasks stand in for database or HTTP waits. The CPU is not what limits the pool of four: it is the number of threads that can wait at the same time.

Graceful shutdown

When a deployment stops an instance, running work should finish rather than be cut off. Three settings cover the usual cases:

PROPERTIES
server.shutdown=graceful
spring.lifecycle.timeout-per-shutdown-phase=30s
spring.task.execution.shutdown.await-termination=true
spring.task.execution.shutdown.await-termination-period=30s
spring.task.scheduling.shutdown.await-termination=true
spring.task.scheduling.shutdown.await-termination-period=30s

With server.shutdown=graceful, the web server stops accepting new requests, lets in-flight requests complete (up to the phase timeout) and then the context closes. The await-termination pair makes the async executor and the scheduler wait for running tasks before the JVM exits. Tasks still queued in an executor are normally allowed to run to completion while it waits, so a long queue can exceed your timeout and be abandoned; keep queues short. Your orchestrator's own grace period (for Kubernetes terminationGracePeriodSeconds) must be longer than the Boot timeout, or the container is killed first (Deployment).

Check your understanding

Quick check ยท 5 questions

of 5 answered You scored / 5 ยท perfect!

  1. 1. Why does a slow @Scheduled job delay other scheduled jobs in a default Boot application?

    The default spring.task.scheduling.pool.size is 1, so jobs run one at a time. Increase the pool, keep jobs short, or enable virtual threads.
  2. 2. How many fields does a Spring @Scheduled cron expression have?

    Spring's cron format is second, minute, hour, day-of-month, month, day-of-week. Writing a five-field expression shifts every meaning.
  3. 3. A pool has core size 2, max size 8 and an unbounded queue. How many threads will it ever use?

    Threads beyond the core size are created only when the queue is full. An unbounded queue never fills, so max-size is never reached.
  4. 4. You call an @Async method from another method in the same class. What happens?

    Like @Transactional, @Async works through a proxy. A call on this never goes through it, so the body runs on the calling thread.
  5. 5. What does spring.threads.virtual.enabled=true NOT do?

    Virtual threads help workloads that mostly wait on I/O. CPU-bound work is limited by cores, not by the number of threads.

Summary

  • @Scheduled supports fixedRate, fixedDelay and six-field cron (with a zone); the default scheduler has a single thread.
  • Every application instance runs its schedules; use a lock, a single scheduler instance or an external trigger, and make jobs idempotent.
  • @Async runs a method on an executor through a proxy: no self-invocation, no inherited transaction or security context, and not durable.
  • Pools add threads beyond core size only when the queue is full; Boot's default queue is unbounded, so bound it on purpose.
  • spring.threads.virtual.enabled=true moves requests, async tasks and scheduled jobs to virtual threads, which suits I/O-bound work.
  • Configure graceful shutdown for the server, the executor and the scheduler, with timeouts shorter than the orchestrator's grace period.

Next: Messaging and Events Between Services.