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
‹ swipe to step through ›
Walkthrough
Space play
←→ step
click any line
Three takeaways
- 1@Scheduled with a cron expression lets Spring run recurring maintenance without external schedulers.
- 2Wrapping the job in @Transactional makes the multi-repository deletes commit or roll back as one unit.
- 3Deriving a cutoff Instant keeps retention logic in one place and lets each repository query filter by it.
Related explainers
java
@Component public class RateLimitingFilter extends OncePerRequestFilter { private static final int MAX_REQUESTS = 100;
How a rate-limiting filter works in Spring
rate limiting
concurrency
servlet filter
Advanced
8 steps
java
public List<Employee> parseEmployees(Path csvPath) throws IOException { List<Employee> employees = new ArrayList<>(); try (BufferedReader reader = Files.newBufferedReader(csvPath, StandardCharsets.UTF_8)) {
Parsing a CSV into typed objects in Java
csv-parsing
file-io
try-with-resources
Intermediate
7 steps
java
public final class RetryExecutor { private final int maxAttempts; private final Duration initialDelay;
Exponential backoff retry in Java
retry
exponential-backoff
jitter
Intermediate
8 steps
typescript
import { ArgumentsHost, Catch, ExceptionFilter,
A catch-all exception filter in NestJS
error-handling
exception-filter
http
Intermediate
8 steps
java
import java.util.LinkedHashMap; import java.util.Map; import java.util.concurrent.locks.ReentrantReadWriteLock;
A thread-safe LRU cache in Java
lru-cache
concurrency
linkedhashmap
Intermediate
7 steps
typescript
import { Module, Injectable } from '@nestjs/common'; import { ConfigModule, ConfigService } from '@nestjs/config'; import * as Joi from 'joi';
Validated, typed config in NestJS
configuration
validation
dependency-injection
Intermediate
6 steps
Share this explainer
Here's the card — post it anywhere.
Made with highlit — turn any snippet into a walkthrough like this in about a minute.
Explain your code
Embed this explainer
Drop the interactive walkthrough into a blog or docs. Views never cost a credit.
<iframe src="https://highlit.co/explainers/how-a-scheduled-cleanup-job-runs-in-spring-explained-java-5cd6/embed?autoplay=1" width="100%" height="520" loading="lazy" style="border:0"></iframe>
Autoplay is on by default — add ?autoplay=0 to start paused.