BBackend CourseLeroy Labs
0/0
Search the course

Scheduled jobs with cron, fixedDelay, sweepers & job observability

@Scheduled cron vs fixedRate vs fixedDelay, zone-aware cron, writing robust sweepers (batching, per-item error handling), recording job runs, and the multi-instance problem (ShedLock).

● intermediateHostel-Web-AppReport-Manager-2IR3D (Kontentt)SperoTek (in dev)

The concept

@EnableScheduling   // once, on a @Configuration
// ...
@Scheduled(fixedRate = 300_000)            // start every 5 min (measured start to start)
@Scheduled(fixedDelay = 3_600_000)         // wait 1 h AFTER the previous run finishes
@Scheduled(cron = "0 0 9 5 * *", zone = "Africa/Accra")   // 09:00 on the 5th of each month
@Scheduled(fixedRateString = "${hostel.sweeper.rate:300000}")  // configurable

Spring cron format: six fields

second minute hour day-of-month month day-of-week
"0 0 0 1 1,4,7,10 *"   -> midnight on 1 Jan, Apr, Jul, Oct (quarter start)
"0 */15 * * * *"       -> every 15 minutes
"0 30 3 * * *"         -> 03:30 daily

By default all @Scheduled methods share one thread, so a slow job delays the rest. Set spring.task.scheduling.pool.size.

A robust sweeper

@Scheduled(fixedRateString = "${hostel.sweeper.rate:300000}")
public void expireUnpaidBookings() {
    List<Booking> due = bookings.findApprovedWithPaymentExpiredBefore(Instant.now(clock));
    for (Booking b : due) {
        try {
            bookingService.expire(b.getId());       // own transaction per item
        } catch (Exception e) {
            log.error("[SWEEPER] failed to expire {}", b.getId(), e);   // one bad row doesn't stop the rest
        }
    }
}

In your projects

Hostel-Web-Appshared/scheduler/BookingExpiredSweeper.java

Expires APPROVED bookings that weren’t paid by paymentExpiresAt, and auto-rejects waitlist drafts past their deadline. Errors are caught per booking, and there’s a partial index on payment_expires_at WHERE status='APPROVED' that makes the scan cheap. BookingExpiredSweeperTest tests it. A refresh-token cleanup runs daily at midnight.

Report-Manager-2ReminderScheduler · PeriodClosingScheduler · SoftDeletePurgeScheduler · SseHeartbeatScheduler ...

Eleven jobs, including:

  • Monthly reminders (0 0 9 5 * *).
  • Quarter closing (0 0 0 1 1,4,7,10 *).
  • Amendment-window cleanup every 15 minutes.
  • Purges: refresh tokens, export jobs (60 days), audit logs (24 months), soft deletes (12 months in batches).
  • An SSE heartbeat every 25 seconds, which keeps proxies from closing idle streams.
IR3D (Kontentt)19 jobs · system/application/ScheduledJobRecorder

Examples:

  • ClipViewIngestionJob (configurable, 15 minutes).
  • CampaignActivationJob (60 seconds).
  • RevenueSweepJob (03:30).
  • WithdrawalReconciliationJob (5 minutes).
  • Nightly LedgerReconciliationJob.
  • AccountLifecycleJob (30-day deletion purge).

ScheduledJobRecorder stores each run (start, end, status, error) and shows it in an admin “Background jobs” view. You can see failed jobs without digging through logs.

SperoTek (in dev)ApprovalEscalator · FailedEmailResubmitter · UndeliveredEmailMonitor · ReportExportService
  • Approvals escalate after 15 minutes.
  • Failed emails are resubmitted every 5 minutes, up to 12 attempts, in batches of 50.
  • An undelivered-email monitor runs hourly with 14-day retention.
  • Export cleanup runs hourly.

Alternatives

Tool Notes
@Scheduled (yours) Built in; single instance unless locked
@Scheduled + ShedLock Cluster-safe
Quartz (JDBC JobStore) Clustering, misfire handling, persistent triggers
JobRunr / db-scheduler Persistent jobs with retries and a dashboard
Cloud schedulers (EventBridge, Cloud Scheduler, Render Cron Jobs) Trigger an endpoint or a container on a schedule
Postgres pg_cron Jobs inside the DB
  • Missed runs. If the app is down at 03:30, @Scheduled won’t catch up. Design jobs to process “everything due”, not “today’s items”.
  • Batch and commit. Large purges should commit in chunks.
  • Reconciliation jobs. They compare your state to an external source of truth (Paystack, the ledger) and alert on drift. This is a key reliability pattern.
  • Zone and DST. Pass zone = for business schedules (money and time lesson).

Check yourself

1. fixedDelay=60000 with a run that takes 90s. Next start?
2. Two instances, plain @Scheduled payout job. Risk?
3. What does "0 0 0 1 1,4,7,10 *" mean?