I have been trying to send notifications to my customers once. I'm using kubernetes and I create multiple spring boot applications because I have 2 replicas. This is all fine but when the scheduler runs, each one of them can send notifications. I have looked a little bit at quartz but the config seems to be a little complicated. Is there an easy way to do so?
@Scheduled(fixedDelayString = "300000")
public void sendFlowerNotification() {
//Code
}
scheduler-locking. set scheduler-locking show scheduler-locking. On some operating systems, control the scheduling of other threads (those not being traced) in the debuggee. The value is one of on , off , or step .
ShedLock makes sure that your scheduled tasks are executed at most once at the same time. If a task is being executed on one node, it acquires a lock which prevents execution of the same task from another node (or thread).
It executes the jobs simultaneously on every node instead. In this short tutorial, we'll look at ShedLock — a Java library that makes sure our scheduled tasks run only once at the same time and is an alternative to Quartz.
Another way to stop the scheduler would be manually canceling its Future. In the cases with multiple scheduler tasks, then we can maintain the Future map inside of the custom scheduler pool but cancel the corresponding scheduled Future based on scheduler class.
You can also use dlock to execute a scheduled task only once over multiple nodes. You can simply do something like below.
@Scheduled(fixedDelayString = "300000")
@TryLock(name = "flowerNotification", owner = POD_NAME, lockFor = THREE_MINUTES)
public void sendFlowerNotifications() {
List<Notification> notifications = notificationService.getNotifications();
for(Notification notification: notifications){
sendNotification(notification);
}
}
You can send the POD_NAME to spring as an environment variable. dlock would automatically handle it.
env:
- name: POD_NAME
valueFrom:
fieldRef:
fieldPath: metadata.name
See the article about using it.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With