java 38 lines · 6 steps

How a scheduled cleanup job runs in Spring

A Spring component runs a nightly, transactional purge of stale sessions and revoked tokens on a cron schedule.

Explained by highlit
1package com.example.maintenance;
2 
3import org.slf4j.Logger;
4import org.slf4j.LoggerFactory;
5import org.springframework.scheduling.annotation.Scheduled;
6import org.springframework.stereotype.Component;
7import org.springframework.transaction.annotation.Transactional;
8 
9import java.time.Instant;
10import java.time.temporal.ChronoUnit;
11 
12@Component
13public class ExpiredSessionCleanupJob {
14 
15 private static final Logger log = LoggerFactory.getLogger(ExpiredSessionCleanupJob.class);
16 
17 private final SessionRepository sessionRepository;
18 private final AuditTokenRepository auditTokenRepository;
19 
20 public ExpiredSessionCleanupJob(SessionRepository sessionRepository,
21 AuditTokenRepository auditTokenRepository) {
22 this.sessionRepository = sessionRepository;
23 this.auditTokenRepository = auditTokenRepository;
24 }
25 
26 @Scheduled(cron = "0 30 2 * * *", zone = "UTC")
27 @Transactional
28 public void purgeStaleData() {
29 Instant cutoff = Instant.now().minus(30, ChronoUnit.DAYS);
30 log.info("Starting nightly cleanup for records older than {}", cutoff);
31 
32 int sessions = sessionRepository.deleteByLastAccessedBefore(cutoff);
33 int tokens = auditTokenRepository.deleteByRevokedTrueAndUpdatedAtBefore(cutoff);
34 
35 log.info("Nightly cleanup complete: removed {} sessions and {} revoked tokens",
36 sessions, tokens);
37 }
38}
01 / 01
STEP 01

Walkthrough

Space play step click any line
Three takeaways
  1. 1@Scheduled with a cron expression lets Spring run recurring maintenance without external schedulers.
  2. 2Wrapping the job in @Transactional makes the multi-repository deletes commit or roll back as one unit.
  3. 3Deriving a cutoff Instant keeps retention logic in one place and lets each repository query filter by it.

Related explainers

Share this explainer

Here's the card — post it anywhere.

How a scheduled cleanup job runs in Spring — share card
Made with highlit — turn any snippet into a walkthrough like this in about a minute.
Explain your code