Video in progress
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
@Scheduledmethods run on a single thread. If one hangs, the rest stop too. Increasespring.task.scheduling.pool.size. - If a
fixedRatejob 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
zoneexplicitly 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.
Sign up to mark studied questions and save your progress.