Spring Boot Tutorial 0/110 lessons ~6 min read Lesson 54

    Scheduling Tasks

    Orders needs recurring work: purge abandoned drafts, remind unpaid checkouts, reconcile inventory snapshots.

    Course progress0%
    Focus
    12 guided sections
    Practice signal
    Examples included
    Career prep
    Interview Q&A included

    Introduction

    Orders needs recurring work: purge abandoned drafts, remind unpaid checkouts, reconcile inventory snapshots.

    Boot 3's @EnableScheduling and @Scheduled run methods on cron, fixed rate, or fixed delay. Perfect for a single replica — dangerous when every pod runs the same job.

    For multi-instance clusters, add ShedLock (DB/Redis lock) or move to a clustered scheduler / queue-triggered workers.

    This lesson schedules TechLearningPRO Orders chores safely and keeps jobs idempotent.

    Purpose of this lesson

    Enable and design idempotent @Scheduled jobs for Orders, including multi-replica caveats on Boot 3.

    Understanding the topic

    Scheduling is in-process until you add distributed coordination.

    • @EnableScheduling: turns on the scheduler infrastructure.
    • cron / fixedRate / fixedDelay: choose based on overlap needs.
    • zone: always set timezone for business cron.
    • idempotency: safe if the job runs twice.
    • distributed: ShedLock, Quartz cluster, or external scheduler.

    Step-by-step explanation

    1. Add a @Configuration with @EnableScheduling.
    2. Implement PurgeDraftOrdersJob with a UTC cron.
    3. Make the delete query bounded and idempotent.
    4. If running multiple pods, add ShedLock around the method.

    Informative example

    Nightly draft purge for Orders.

    java
    @Configuration
    @EnableScheduling
    public class SchedulingConfig {}
    @Component
    public class PurgeDraftOrdersJob {
    private final OrderRepository orders;
    public PurgeDraftOrdersJob(OrderRepository orders) {
    this.orders = orders;
    }
    @Scheduled(cron = "0 0 2 * * *", zone = "UTC")
    public void purgeOldDrafts() {
    Instant cutoff = Instant.now().minus(30, ChronoUnit.DAYS);
    int n = orders.deleteDraftsOlderThan(cutoff);
    log.info("Purged {} draft orders older than {}", n, cutoff);
    }
    }
    // Multi-replica sketch (ShedLock)
    // @SchedulerLock(name = "purgeOldDrafts", lockAtMostFor = "PT30M")
    // public void purgeOldDrafts() { ... }

    Real-world use

    With three Orders replicas, a naive @Scheduled reminder emailed customers three times at 09:00. Adding a Redis ShedLock made only one pod send reminders while others skipped.

    Security implications

    Scheduled tasks often hold elevated data access.

    • Do not expose an unauthenticated HTTP trigger that runs the same job.
    • Log order ids, not PII payloads, in job summaries.
    • Lock names and schedules are not secrets — credentials used by jobs still are.

    Best practices

    • Idempotent jobs; metrics for success/fail counts.
    • Use fixedDelay when the previous run must finish first.
    • Prefer queue consumers for work that must scale with backlog.

    Common mistakes

    • Assuming cron runs once in Kubernetes without a lock.
    • Long jobs overlapping themselves on fixedRate without a guard.
    • Catching and swallowing all exceptions so failures stay invisible.

    Advanced interview questions

    Interview Prep

    Practice concise answers, then expand each card for the explanation.

    3 questions
    1BeginnerQuestionDoes @Scheduled run once per cluster?+

    Answer

    No — each application instance schedules independently unless you add distributed locking or an external scheduler.
    2IntermediateQuestionfixedRate vs fixedDelay?+

    Answer

    fixedRate schedules by start-to-start interval; fixedDelay waits for completion then delays — better to avoid overlap.
    3IntermediateQuestionWhen prefer Kafka consumers over @Scheduled?+

    Answer

    When work volume scales with events/backlog and you need competing consumers rather than clock-driven batch on every node.

    Hands-on exercise

    Lab. Create a draft-purge @Scheduled job with a short cron for local testing. Run two application instances and observe double execution; then add a lock (or document why a single replica is required).

    Summary

    Scheduling tasks keeps TechLearningPRO Orders tidy on a clock — with distributed locks when more than one Boot instance is alive.

    Ready to mark this lesson complete?Track your journey across the entire course.