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
typescript
import { Injectable, signal, computed, effect, inject } from '@angular/core'; import { DOCUMENT } from '@angular/common'; export type Theme = 'light' | 'dark';
A signal-based theme service in Angular
signals
reactivity
dependency-injection
Intermediate
7 steps
java
public final class CaseConverter { private static final Pattern CAMEL_BOUNDARY = Pattern.compile("([a-z0-9])([A-Z])|([A-Z]+)([A-Z][a-z])");
Converting camelCase to snake_case in Java
regex
string-manipulation
utility-class
Intermediate
7 steps
java
@Component public class RegionCacheWarmer implements SmartInitializingSingleton { private static final Logger log = LoggerFactory.getLogger(RegionCacheWarmer.class);
Warming a Spring cache at startup
caching
startup-hook
dependency-injection
Intermediate
7 steps
java
public final class EmailNormalizer { private static final Pattern EMAIL_PATTERN = Pattern.compile( "^[A-Za-z0-9._%+-]+@[A-Za-z0-9.-]+\\.[A-Za-z]{2,}$"
Normalizing email addresses in Java
validation
regex
normalization
Intermediate
8 steps
python
from datetime import date, timedelta from typing import Annotated from fastapi import APIRouter, Depends, Query
Validating date ranges with FastAPI dependencies
dependency-injection
validation
pydantic
Intermediate
6 steps
java
@RestController @RequestMapping("/api/products") @RequiredArgsConstructor public class ProductBatchController {
Batch JSON Merge Patch in Spring
json-merge-patch
rest-api
partial-update
Intermediate
8 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.