8 Haziran 2023 Perşembe

SpringScheduling Shedlock From Configuration

Giriş
Açıklaması şöyle
Locking without a framework
It is possible to use ShedLock without a framework
Şöyle yaparız. Burada LockingTaskExecutor belirtilen Runnable nesnesini belirtilen lock ismi ile birlikte çalıştırır.
LockingTaskExecutor executor = new DefaultLockingTaskExecutor(lockProvider);
... Instant lockAtMostUntil = Instant.now().plusSeconds(600); executor.executeWithLock(runnable, new LockConfiguration("lockName", lockAtMostUntil));
Örnek
Şöyle yaparız. Bu örnekte Spring kodları dolaşılıyor ve her Cron işi LockingTaskExecutor ile sarmalanıyor
import org.springframework.scheduling.annotation.SchedulingConfigurer
import org.springframework.scheduling.config.CronTask import org.springframework.scheduling.config.ScheduledTaskRegistrar; import net.javacrumbs.shedlock.core.LockConfiguration; import net.javacrumbs.shedlock.core.LockingTaskExecutor; @Configuration @RequiredArgsConstructor public class SchedulerConfig implements SchedulingConfigurer { private final LockingTaskExecutor lockingTaskExecutor; private final TaskProperties taskProperties; private final Map<String, ScheduledTask> scheduledTaskMap = new HashMap<>(); private ScheduledTaskRegistrar taskRegistrar; public Executor taskExecutor() { return Executors.newScheduledThreadPool(100); } @Override public void configureTasks(ScheduledTaskRegistrar taskRegistrar) { this.taskRegistrar = taskRegistrar; taskRegistrar.setScheduler(taskExecutor()); taskProperties.getTasks().forEach(this::addTask); } public void addTask(TaskProperty taskProperty) { Runnable task = () -> log.info("Running task with name {}", taskProperty.getName()); ScheduledTask scheduledTask = taskRegistrar.scheduleCronTask( new CronTask(() -> lockingTaskExecutor.executeWithLock(task, new LockConfiguration(Instant.now(), taskProperty.getName(), taskProperty.getLockAtMostFor(), taskProperty.getLockAtLeastFor())) , taskProperty.getCron())); scheduledTaskMap.put(taskProperty.getName(), scheduledTask); } }


Hiç yorum yok:

Yorum Gönder