Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Java Spring Scheduler Lock

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
}
like image 666
avigaild Avatar asked Oct 27 '18 17:10

avigaild


People also ask

What is a scheduler lock?

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 .

What is the use of ShedLock?

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).

What is ShedLock in Java?

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.

How do I stop a scheduled spring job?

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.


1 Answers

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.

like image 146
Will Hughes Avatar answered Sep 17 '22 16:09

Will Hughes