This application demonstrates the usage of ShedLock with Spring Boot for distributed task scheduling. ShedLock ensures that scheduled tasks run only once across multiple application instances in a distributed environment.
- ReportDataEntity: JPA entity for storing report data with status tracking
- Scheduled Tasks: Three different scheduled tasks demonstrating ShedLock usage:
processPendingReports: Processes pending reports every 30 secondsgenerateSampleReports: Generates sample reports every 2 minutescleanupOldReports: Cleans up old completed reports every 5 minutes
- REST API: Endpoints to monitor and query report data
- Data Initialization: Automatically creates sample data on startup
- Java 21
- MySQL database
- Gradle
- Create a MySQL database named
spring_shedlock_example - Update database credentials in
application.propertiesif needed
- Start MySQL database
- Run the application:
./gradlew bootRun
GET /api/reports- Get all reportsGET /api/reports/status/{status}- Get reports by status (PENDING, PROCESSING, COMPLETED, FAILED)GET /api/reports/user/{userId}- Get reports by user IDGET /api/reports/stats- Get report statistics
The application uses ShedLock with MySQL as the lock provider. The lock table will be automatically created as shedlock in the database.
-
Process Pending Reports (every 30 seconds)
- Lock name:
processPendingReports - Processes all PENDING reports and marks them as COMPLETED
- Simulates 2-second processing time per report
- Lock name:
-
Generate Sample Reports (every 2 minutes)
- Lock name:
generateSampleReports - Creates new sample reports with PENDING status
- Lock name:
-
Cleanup Old Reports (every 5 minutes)
- Lock name:
cleanupOldReports - Removes COMPLETED reports older than 1 hour
- Lock name:
On startup, the application creates 8 sample reports:
- 5 PENDING reports (will be processed by scheduled tasks)
- 2 COMPLETED reports (one old, one recent)
- 1 FAILED report
Watch the application logs to see ShedLock in action:
- Scheduled tasks will log their execution
- Only one instance of each task will run at a time
- Reports will be processed and status updated automatically
To test ShedLock's distributed locking:
- Start multiple instances of the application
- Observe that scheduled tasks run only on one instance
- If one instance fails, another will take over the task execution