kdlug
10/15/2019 - 8:58 AM

Shedlock

// https://www.baeldung.com/shedlock-spring
@Component
@ConditionalOnProperty("app.synchronizer.enabled")
public class Synchronizer {
    private Logger logger = LogManager.getLogger(Synchronizer.class);
    private static final String SCHEDULER_PREFIX = "Synchronizer"; // ClassName_methodName

    @Scheduled(cron = "${app.synchronizer.cron}")
    @SchedulerLock(name = SCHEDULER_PREFIX + "cron", lockAtLeastForString = "${app.synchronizer.lock-at-least-for}", lockAtMostForString = "${app.synchronizer.lock-at-most-for}")
    public void cron() throws InterruptedException {
      ...
    }
    
    @Scheduled(fixedRateString = "#{${app.synchronizer.fixed-rate}*1000}")
    @SchedulerLock(name = SCHEDULER_PREFIX + "fixed", lockAtLeastForString = "${app.synchronizer.lock-at-least-for}", lockAtMostForString = "${app.synchronizer.lock-at-most-for}")
    public void fixed() throws InterruptedException {
      ...
    }
}
  app:
    synchronizer:
      enabled: true
      fixed-rate: 120 # seconds
      cron: "*/15 * * * * ?" // every 15 minutes
      lock-at-least-for: PT5M // this method will hold the lock for 5 minutes, at a minimum. In other words, that means that this method can be run by ShedLock no more often than every five minutes.
      lock-at-most-for: PT15M // how long the lock should be kept in case the executing node dies. It will be locked for no longer than 15 minutes.
      default-lock-at-most-for: PT5M
dependencies {
	implementation('net.javacrumbs.shedlock:shedlock-spring:2.5.0')
	implementation('net.javacrumbs.shedlock:shedlock-provider-mongo:2.5.0')
}
@Configuration
@EnableScheduling
@EnableSchedulerLock(defaultLockAtMostFor = "${app.synchronizer.default-lock-at-most-for}")
@Profile("!disablescheduler")
public class Scheduler {
    @Bean
    public LockProvider lockProvider(MongoTemplate mongoTemplate) {
        return new MongoLockProvider(mongoTemplate.getCollection("schedulerLocks"));
    }
}