Java Spring Scheduler Lock

avigaild :

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
}
Will Hughes :

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.

Guess you like

Origin http://43.154.161.224:23101/article/api/json?id=78503&siteId=1