Video in progress

Middle 🌱 Spring

What's the difference between fixedRate, fixedDelay and cron in @Scheduled?

fixedRate counts time from when the previous run started, fixedDelay — from when the previous run finished. cron follows the calendar, for example every day at 03:00.

📖 Answer

@EnableScheduling
@Configuration class SchedulingConfig { }

@Component
class Jobs {
    @Scheduled(fixedRate = 60_000)          // at the start of every minute
    void pollRates() { ... }

    @Scheduled(fixedDelay = 30, timeUnit = TimeUnit.SECONDS, initialDelay = 10)
    void sendQueuedEmails() { ... }        // waits 30 s after finishing, then runs again

    @Scheduled(cron = "0 0 3 * * *", zone = "Asia/Tashkent")
    void nightlyCleanup() { ... }          // every day at 03:00
}

Subtle points:

  • By default all @Scheduled methods run on a single thread. If one hangs, the rest stop too. Increase spring.task.scheduling.pool.size.
  • If a fixedRate job takes longer than 60 s, the next run waits for the previous one to finish (with a single thread) — runs don't overlap, but they fall behind.
  • Set zone explicitly in cron — the server may be on UTC.
  • If the app runs as 3 instances, the job runs 3 times too. In production people often notice this late — after the customer got the email three times. If it must run on one instance only, add ShedLock or a database lock.