Scheduling Tasks
Orders needs recurring work: purge abandoned drafts, remind unpaid checkouts, reconcile inventory snapshots.
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
- Add a
@Configurationwith@EnableScheduling. - Implement
PurgeDraftOrdersJobwith a UTC cron. - Make the delete query bounded and idempotent.
- If running multiple pods, add ShedLock around the method.
Informative example
Nightly draft purge for Orders.
@Configuration@EnableSchedulingpublic class SchedulingConfig {}@Componentpublic 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.
1BeginnerQuestionDoes @Scheduled run once per cluster?+
Answer
2IntermediateQuestionfixedRate vs fixedDelay?+
Answer
3IntermediateQuestionWhen prefer Kafka consumers over @Scheduled?+
Answer
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.