🌷 Those who establish great achievements in ancient times are not only extraordinary talents but also have an unyielding will.
🎐 Personal CSDN homepage – Micro McRobot’s Blog
🐥《Docker Hands-On Tutorial》column is based on the latest CentOS version and provides hands-on Docker tutorials from basics to practical applications.
🌺《RabbitMQ》column mainly introduces a series of RabbitMQ tutorials using Java, covering basic knowledge to project practices.
🌸《Design Patterns》column uses real-life scenarios as examples to explain design patterns, helping you gain a clearer understanding.
💕《Jenkins Hands-On》column focuses on Jenkins + Docker hands-on tutorials to help you quickly master project CI/CD, offering the latest 2024 practical guides.
🌞《Spring Boot》column mainly introduces commonly applied functions and techniques in our daily work projects, with complete code examples provided.
Integrating Spring Boot with ShedLock to Handle Task Rescheduling Issues
- Introduction
- What is ShedLock?
- Problem of repeated execution of scheduled tasks
- Using ShedLock to solve the problem of repeated execution of scheduled tasks
- Conclusion
Introduction
In distributed systems, the execution of scheduled tasks often needs to consider concurrent execution across multiple instances.Assuming a scheduled task would run concurrently on multiple nodes, which could lead to repeated execution and even data anomalies or system inconsistencies.To solve this problem, ShedLock is a simple and effective solution that ensures only one node executes a specific scheduled task at any given time in a distributed environment.
What is ShedLock?
ShedLock is a lightweight Java library forsolving the problem of repeated execution of scheduled tasks in distributed systems.Its core idea is to lock in the database, ensuring that only one node can execute a specific task at a given time in a distributed environment. ShedLock can be used with Spring Scheduler, Quartz, and other scheduled task frameworks.
GitHub open source address: https://github.com/lukas-krecan/ShedLock. Currently has 3.7K stars. Everyone can also study the documentation more systematically to learn how to apply ShedLock.
How does ShedLock work?
❶ When a scheduled task is executed, ShedLock will attempt to acquire a lock for that task in the database.
❷ If the current node successfully acquires the lock, it executes the scheduled task.
❸ If the current node fails to acquire the lock (another node has already acquired it), the task is skipped and will be attempted again on the next schedule.
Problem of repeated execution of scheduled tasks
In distributed applications, scheduled tasks are often run by multiple instances, each executing the task according to its own scheduling plan. For example, suppose there is a scheduled task responsible for synchronizing data from an external system. If this task is executed simultaneously on multiple instances, it will result in repeated data synchronization, leading to issues such as data inconsistency and duplicate processing.
Typical scenarios
Let’s simulate a scenario where, in an e-commerce system, a scheduled task is responsible for synchronizing inventory data to a third-party inventory management system. If this task is executed simultaneously on multiple nodes, it may lead to:
1、Repeated inventory update requests.
2、Data inconsistency or data loss.
3、High system load causing performance bottlenecks.
Solving repeated execution of scheduled tasks using ShedLock
Next, the blogger will demonstrate how to solve the problem of repeated task execution using Spring Boot and ShedLock. Hopefully, this can serve as a reference for everyone!
❶ Adding dependencies
First, ensure that our pom.xml contains the necessary dependencies. We need to add dependencies for Spring Boot Starter, Spring Scheduling, and ShedLock.
The blogger uses MySQL as the database for initializing ShedLock, so we introduce the dependency
shedlock–provider–jdbc–template. You can choose according to your actual situation based on the author’s documentation. As shown in the following figure:
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 |
<dependencies> <!— Spring Boot Starter Web —> <dependency> <groupId>org.springframework.boot</groupId> <artifactId>spring–boot–starter–web</artifactId> </dependency> <!— Spring Boot Scheduler —> <dependency> <groupId>org.springframework.boot</groupId> <artifactId>spring–boot–starter–scheduled</artifactId> </dependency> <!— ShedLock Core —> <dependency> <groupId>net.javacrumbs.shedlock</groupId> <artifactId>shedlock–spring</artifactId> <version>6.2.0</version> </dependency> <!— ShedLock JDBC —> <dependency> <groupId>net.javacrumbs.shedlock</groupId> <artifactId>shedlock–provider–jdbc–template</artifactId> <version>6.2.0</version> </dependency> <!— MySQL JDBC Driver —> <dependency> <groupId>mysql</groupId> <artifactId>mysql–connector–java</artifactId> </dependency> </dependencies> |
Version Compatibility Dependencies:
ShedLock Version | Minimum JVM Version | Tested With |
---|---|---|
6.x.x | 17 | Spring 6.2, 6.1 Spring Boot 3.4, 3.3 Micronaut 4 |
5.x.x | 17 | Spring 6.1, 6.0 Spring Boot 3.4, 3.3, 3.2 Micronaut 3, 4 |
4.x.x | 8 | Spring 6.0, 5.3 Spring Boot 3.0, 2.7, 2.6 |
3.x.x | 8 | Spring 5.2, 5.1 Spring Boot 2.2, 2.1 |
2.x.x | 8 | Spring 5.1, 5.0 Spring Boot 2.1 |
1.x.x | 8 | Spring 5.0 Spring Boot 2.0 |
❷ Configure the Database
ShedLock needs to store lock information in the database. Here, the blog owner uses MySQL to store locks. First, create a table named shedlock to store lock data.
1 2 3 4 5 6 |
CREATE TABLE shedlock ( name VARCHAR(64) PRIMARY KEY, lock_until TIMESTAMP(3) NOT NULL, locked_at TIMESTAMP(3) NOT NULL, locked_by VARCHAR(255) NOT NULL ); |
The fields of this table and their meanings are as follows:
- name: Lock name used to distinguish different tasks.
- lock_until: Expiration time of the lock. The lock should be released after the task is completed.
- locked_at: Time when the lock was created.
- locked_by: Which node holds the lock.
❸ Configure ShedLock
Next, we configure ShedLock in a Spring Boot configuration class. Below is a basic configuration example:
1 2 3 4 5 6 7 8 |
import net.javacrumbs.shedlock.spring.annotation.EnableSchedulerLock; import org.springframework.context.annotation.Configuration; import org.springframework.scheduling.annotation.EnableScheduling; @Configuration @EnableScheduling @EnableSchedulerLock(defaultLockAtMostFor = “30m”) //Default lock expiration time is 30 minutes public class ShedLockConfig { } |
Note Explanation:
@EnableSchedulerLock: Enable the
ShedLock feature, with the
defaultLockAtMostFor parameter specifying the maximum expiration time for the lock. If the task execution exceeds this duration, the lock will be released.
@EnableScheduling: Enable Spring’s scheduling functionality.
❹ Create Scheduled Tasks
Next, we create a scheduled task and add ShedLock locking to it, ensuring that only one instance will execute the task in a distributed environment.
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 |
package com.example; import net.javacrumbs.shedlock.spring.annotation.SchedulerLock; import org.springframework.scheduling.annotation.Scheduled; import org.springframework.stereotype.Service; @Service public class DataSyncService { /** * Use @SchedulerLock annotation to ensure this task is only executed on one node */ @Scheduled(fixedRate = 5000) // Execute every 5 seconds @SchedulerLock(name = “syncInventoryTask”, lockAtMostFor = “5m”, lockAtLeastFor = “5m”) public void syncInventory() { System.out.println(“Syncing inventory data…”); // Simulate inventory synchronization operations try { Thread.sleep(3000); // Simulate execution taking 3 seconds } catch (InterruptedException e) { Thread.currentThread().interrupt(); } System.out.println(“Inventory synchronization completed!”); } } |
In the code above, we applied the @SchedulerLock annotation on the syncInventory method. We specified the lock name as syncInventoryTask and set the maximum lock duration to 5 seconds.
- name: The name of the lock, ensuring a unique identifier for each scheduled task.
- lockAtMostFor: The maximum time the lock can remain active, preventing the lock from being released if the task encounters an exception.
- lockAtLeastFor: The minimum duration the lock should hold, ensuring the lock persists for a certain period of time.
❺ Configure Database Connection
Finally, configure our database connection information in application.properties or application.yml
1 2 3 4 5 |
spring.datasource.url=jdbc:mysql://localhost:3306/your_database spring.datasource.username=root spring.datasource.password=your_password spring.datasource.driver–class–name=com.mysql.cj.jdbc.Driver spring.jpa.hibernate.ddl–auto=update |
❻ Start application testing
Finally, we start the Spring Boot application and check the console output. You will see the syncInventory task running every 5 seconds, but only one node can successfully execute the task at any moment to avoid issues caused by concurrent execution across multiple nodes.
Summary
I believe that through the examples in this article, we demonstrated how to use ShedLock to solve the problem of repeated task execution in distributed systems. ShedLock provides a simple and effective way to ensure that scheduled tasks are not executed multiple times in environments with multiple instances, avoiding inconsistencies in data.
- Application scenarios: distributed scheduled tasks, task scheduling, data synchronization, etc.
- Advantages: easy to use, no complex configuration required, supports various storage methods (such as JDBC, MongoDB, Redis, etc.)
If this article has been helpful to you, please give the blogger a thumbs-up with a three-connection support. If you have any questions or suggestions, feel free to leave a comment!
10 responses to “**Spring Boot Integration with ShedLock for Addressing Repeated Task Executions**”
-
This is a fantastic resource for anyone looking to handle task concurrency in Spring Boot applications. Highly recommended for both beginners and experienced developers!
-
Thanks for the insightful guide! The problem of repeated task executions is something many developers face, and this article offers a clear solution using ShedLock.
-
The combination of Spring Boot and ShedLock seems like a robust solution for task rescheduling issues. I’ll definitely look into implementing this in my projects.
-
ShedLock is a powerful tool, and this article makes it accessible even to those new to distributed systems. Well done!
-
I appreciate the detailed walk-through, especially the part about configuring the database connection. This will be helpful for setting up ShedLock properly.
-
The article does an excellent job breaking down the problem and providing a practical solution using ShedLock. A must-read for developers working with scheduled tasks!
-
This tutorial is exactly what I needed. It simplifies the process of implementing ShedLock in Spring Boot applications. Highly recommended!
-
Thanks for sharing this solution! Using ShedLock with Spring Boot is a game-changer for avoiding repeated task executions in distributed environments.
-
Great explanation of how ShedLock works and its integration with Spring Boot. The step-by-step approach makes it easy to follow.
-
This article provides a clear and concise guide on integrating Spring Boot with ShedLock to prevent task rescheduling issues. Perfect for anyone dealing with distributed systems!
- Firedac connecting to MSSQL is slow.
- CreateFile returns INVALID_HANDLE_VALUE issue
- “Nginx Load Balancing Fails to Automatically Switch to Backup”
- “Three Simple Steps to Deploy DeepSeek Locally and Say Goodbye to Server Downtime!”
- What are the main mature categories that JavaScript consists of
- Based on Python and Django for Tourist Attraction Recommendation System
- What is the role of block elements in web front-end
- How to add formulas and special characters in Origin?
- How to Calculate the Calculation Methods of Cumulative Screen Residue and Individual Screen Residue?
- How to View Front-End Operations on the InterSystems IRIS Database
- How to write a program in C language for max(a, b, c)?
- 500 Internal Server Error is a fault code.
- Currently, the efficiency of block hashes is reflected in several key areas:
- “How to Connect Backend, Frontend, and Database in Python”
- Explain why the output is 0 when int a=1==0; in C language.
- “How to resolve ORA-01861: The text does not match the format string”
- [In-Depth Analysis] DeepSeek Large Model Technology Insights: From Architecture to Application – Comprehensive Exploration
- In Using PyWebView, HTML Page Data Requests Always Throw an Error: TypeError: Cannot Read Properties of Undefined (Reading ‘Api’)
- “How to Implement a Carousel Effect Using JavaScript”
- VSCode Unable to Jump to Definition
- How to handle line breaks in a textarea?
- How to Determine Whether a Point Is Within a Sector in JavaScript?
- js schedule code
- “How to handle line breaks in a textarea?”
- MySQL Practical Series: Date Formatting
- In C, what does the tilde symbol mean
- What good frontend frameworks should I choose for PC-end projects
- “How to write the request in the body”
- What Does “OR” Mean in Regular Expressions
- What is the meaning of error code 405
Leave a Reply
You must be logged in to post a comment.