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

    Scheduling Tasks

    @Scheduled runs methods on a cron or fixed-rate schedule.

    Course progress0%
    Focus
    3 guided sections
    Practice signal
    Examples included
    Career prep
    Foundation builder

    Introduction

    @Scheduled runs methods on a cron or fixed-rate schedule. Great for cleanups, syncs, daily reports — bad for distributed jobs (use Quartz or a queue when you have N replicas).

    Informative example

    ts
    @Configuration @EnableScheduling
    public class SchedulingConfig {}
    @Component
    @RequiredArgsConstructor
    public class CleanupJob {
    private final OrderRepository orders;
    // every day at 02:00
    @Scheduled(cron = "0 0 2 * * *", zone = "UTC")
    public void purgeOldDrafts() {
    int n = orders.deleteDraftsOlderThan(Instant.now().minus(30, ChronoUnit.DAYS));
    log.info("Purged {} draft orders", n);
    }
    }

    Best practices

    • Single-replica only — @Scheduled runs on every instance otherwise.
    • Multi-replica → ShedLock + DB/Redis lock, or Quartz cluster.
    • Make jobs idempotent; nothing breaks if the same one runs twice.
    Ready to mark this lesson complete?Track your journey across the entire course.