SchedulerConfig.java

  1. package no.nav.data.common;

  2. import lombok.extern.slf4j.Slf4j;
  3. import net.javacrumbs.shedlock.spring.annotation.EnableSchedulerLock;
  4. import no.nav.data.common.utils.MdcUtils;
  5. import org.springframework.context.annotation.Configuration;
  6. import org.springframework.scheduling.Trigger;
  7. import org.springframework.scheduling.annotation.EnableScheduling;
  8. import org.springframework.scheduling.annotation.SchedulingConfigurer;
  9. import org.springframework.scheduling.concurrent.ConcurrentTaskScheduler;
  10. import org.springframework.scheduling.config.ScheduledTaskRegistrar;

  11. import java.util.Date;
  12. import java.util.concurrent.Executors;
  13. import java.util.concurrent.ScheduledFuture;

  14. @Slf4j
  15. @Configuration
  16. @EnableScheduling
  17. @EnableSchedulerLock(defaultLockAtMostFor = "PT10M", defaultLockAtLeastFor = "PT59s")
  18. public class SchedulerConfig implements SchedulingConfigurer {

  19.     @Override
  20.     public void configureTasks(ScheduledTaskRegistrar taskRegistrar) {
  21.         taskRegistrar.setTaskScheduler(new Scheduler());
  22.     }

  23.     private static class Scheduler extends ConcurrentTaskScheduler {

  24.         public static final String SCHEDULER_NAME = "scheduler";

  25.         public Scheduler() {
  26.             super(Executors.newSingleThreadScheduledExecutor());
  27.         }

  28.         @Override
  29.         public ScheduledFuture<?> schedule(Runnable task, Trigger trigger) {
  30.             return super.schedule(wrap(task), trigger);
  31.         }

  32.         @Override
  33.         public ScheduledFuture<?> scheduleAtFixedRate(Runnable task, Date startTime, long period) {
  34.             return super.scheduleAtFixedRate(wrap(task), startTime, period);
  35.         }

  36.         @Override
  37.         public ScheduledFuture<?> scheduleAtFixedRate(Runnable task, long period) {
  38.             return super.scheduleAtFixedRate(wrap(task), period);
  39.         }

  40.         @Override
  41.         public ScheduledFuture<?> schedule(Runnable task, Date startTime) {
  42.             return super.schedule(wrap(task), startTime);
  43.         }

  44.         @Override
  45.         public ScheduledFuture<?> scheduleWithFixedDelay(Runnable task, Date startTime, long delay) {
  46.             return super.scheduleWithFixedDelay(wrap(task), startTime, delay);
  47.         }

  48.         @Override
  49.         public ScheduledFuture<?> scheduleWithFixedDelay(Runnable task, long delay) {
  50.             return super.scheduleWithFixedDelay(wrap(task), delay);
  51.         }

  52.         private Runnable wrap(Runnable task) {
  53.             return MdcUtils.wrapAsync(task, SCHEDULER_NAME);
  54.         }
  55.     }
  56. }