SteelReed

Search

Search posts, questions…

5. Spring Boot

Cron jobs: cron expressions and @Scheduled in Spring Boot

How Unix, Spring and Quartz cron syntax differ, fixedRate vs fixedDelay, and the traps in @Scheduled: one shared thread, swallowed exceptions, no catch-up, multiple instances with ShedLock, time zones and DST.

17 Nov 20268 min readMid

–

1. The problem

A summary email job @Scheduled(cron = "0 0 7 * * *") works fine on a dev machine. In production on 3 pods, customers get the email three times, at 14:00 instead of 7:00 because the container runs in UTC. The same week, a 40-minute cleanup job makes the every-minute OTP expiry job wait 40 minutes.

2. Key idea

A cron job runs periodically or at a set time. @Scheduled keeps no state and knows nothing about clusters: threads, errors, duplicate runs and time zones are your job.

Unix crontab / Kubernetes CronJob Spring Quartz
Fields 5 6, seconds first 6 or 7, year last
Numeric weekday 0-7 (0, 7 = Sun) 0-7, 1 = MON 1-7, 1 = Sun
Both day-of-month and weekday OR AND not allowed

Use weekday names (MON, FRI): 5L in Spring is the last Friday of the month, in Quartz the last Thursday. Spring example: 0 0/5 * * * * is every 5 minutes.

2.1 How do you prevent duplicate runs across pods?

Approach Use when Don't use when
ShedLock most jobs: one pod runs, the others skip you need catch-up runs or work split across workers
Kubernetes CronJob, concurrencyPolicy: Forbid you run on Kubernetes and want it separate from the app you don't run on Kubernetes
Quartz cluster you need misfire policies, a real distributed scheduler simple jobs: too heavy
A queue (Kafka, a job table) many small units with per-unit retries a single task per day

Locks can still expire, and there are retries and manual runs, so jobs must be idempotent: delete by condition (updated_at < cutoff), write results by a natural key with UNIQUE, store a "sent" record.

3. In Java

JAVA
@Component
class ReportJobs {
    @Scheduled(cron = "0 0 7 * * *", zone = "Asia/Ho_Chi_Minh")   // no zone: 7:00 UTC = 14:00 in Vietnam
    @SchedulerLock(name = "dailySummary", lockAtMostFor = "PT30M", lockAtLeastFor = "PT1M")
    void dailySummary() {
        try {
            summaries.sendForDate(LocalDate.now(clock));   // skips users with a "sent" record
        } catch (Exception e) {
            log.error("dailySummary failed", e);           // Spring's default logs and swallows
            meter.counter("job.failed", "job", "dailySummary").increment();
        }
    }
}
// application.yml
// spring.task.scheduling.pool.size: 4      (default is 1 thread for every job)

lockAtMostFor must be longer than the real run time, or another pod runs in parallel. Other languages: Go typically uses robfig/cron with a DB lock; Node.js has node-cron, with the same multi-instance trap.

fixedRate, fixedDelay, catch-up and daylight saving
  • fixedRate = 60_000: every 60 s from the start of the previous run. fixedDelay: 60 s after the previous run ends.
  • With the default scheduler, fixedRate runs late rather than overlapping; cron skips missed slots. Adding @Async or enabling virtual threads (spring.threads.virtual.enabled=true) makes fixedRate and cron able to overlap.
  • No catch-up: if the app is deploying at 00:00, that run is lost. Fix: run often (hourly) with a data-based condition ("no report for yesterday yet").
  • DST: in zones with daylight saving, 02:30 doesn't exist on one day and happens twice on another. Schedule outside 01:00–03:00, or run in UTC.
  • Heavy jobs belong on a separate bounded executor; the scheduler only "keeps time". Use - as the expression to disable a job via config.

4. Working with AI

Hand to AI: translating a business schedule into a cron expression in the right dialect, generating a test that prints the next 10 runs with CronExpression.next(), configuring ShedLock.

Check yourself in AI-written code:

  • The expression is the right dialect (Spring, 6 fields), with weekday names rather than numbers.
  • Every cron has a zone.
  • With multiple instances there's ShedLock or equivalent; lockAtMostFor exceeds the real run time.
  • The job is idempotent: two runs for the same slot don't send or write twice.
  • There's a metric or alert when the job fails or doesn't run (last successful run time).

5. Exercises

Exercise 1: Review an AI-written reconciliation job

The AI wrote the job below and says "runs at 1 a.m. daily, safe when scaling". The service runs 4 pods in UTC containers. Find the bugs and fix them.

JAVA
@Scheduled(cron = "0 1 * * *")
void reconcile() {
    List<Long> ids = payments.findUnreconciledIdsOfYesterday();
    for (Long id : ids) ledger.insert(new Entry(id, LocalDate.now().minusDays(1)));
}
Solution 1
  • Wrong dialect: 5 fields is Unix; Spring needs 6, so the app won't start. Correct: 0 0 1 * * *.
  • No zone: 1 a.m. UTC is 8 a.m. in Vietnam; "yesterday" is computed in UTC too.
  • 4 pods run it 4 times: every payment lands in the ledger 4 times. Add ShedLock.
  • Not idempotent: add UNIQUE (payment_id) on ledger and upsert, so retries or manual runs don't duplicate.
  • Also: inject a Clock instead of LocalDate.now(); a slot missed during deploy is lost, so check "has day X been reconciled" on the next run.

Exercise 2: Choose how to run a job on Kubernetes

A report export job runs 2 hours nightly and needs 3 GB of RAM. The web service runs 6 pods of 1 GB each. The AI proposes @Scheduled + ShedLock inside the web service. Choose between that and a Kubernetes CronJob, and explain.

Solution 2

Pick the Kubernetes CronJob: the job needs 3 GB and web pods have 1 GB, so running it there means OOMKilled pods or slowed real requests. A CronJob gets its own resources, concurrencyPolicy: Forbid against duplicates, backoffLimit for retries, and isn't lost when the web service deploys.

Keep @Scheduled + ShedLock for light jobs of seconds to minutes that share the service's code and config.

Summary

  • Unix 5 fields, Spring 6, Quartz 6-7 with 1 = Sunday; use weekday names.
  • One thread for all jobs by default; exceptions are swallowed; missed slots aren't caught up.
  • Multiple pods run the job multiple times: ShedLock or a Kubernetes CronJob.
  • Jobs must be idempotent, even with a lock.
  • Always set zone; avoid the DST hours.

Further reading: Deleting old data safely.

Practice interview questions on this topic

All Spring Boot questions →All Microservices questions →

Loading comments…