Friday, July 13, 2018

how to change shceduler times in spring

How to change scheduler times in Spring

 

Imagine that you have scheduler but you want to change time at runtime. What Can you do? Off-course there are ways do solve the problem. So In this article I will write how to implement Trigger interface that is located to the following package: org.springframework.scheduling in the spring-context project.

1. First off all, let's create interface for our logic:

























2. In Spring we have org.springframework.scheduling.Trigger interface:
























So we can write our own implementation. It's very simple. We should just overwrite nextExecutionTime(_) method.  Something like that:


import org.springframework.scheduling.TaskScheduler;
import org.springframework.scheduling.Trigger;
import org.springframework.scheduling.TriggerContext;
import java.util.Date;
import java.util.concurrent.ScheduledFuture;
public class CustomDynamicSchedule extends DynamicSchedule implements Trigger {
private TaskScheduler taskScheduler;
private ScheduledFuture<?> schedulerFuture;
/**
* milliseconds
*/
private long delayInterval;
public CustomDynamicSchedule(TaskScheduler taskScheduler) {
this.taskScheduler = taskScheduler;
}
@Override
public void increaseDelayInterval(Long delay) {
if (schedulerFuture != null) {
schedulerFuture.cancel(true);
}
this.delayInterval += delay;
schedulerFuture = taskScheduler.schedule(() -> { }, this);
}
@Override
public void decreaseDelayInterval(Long delay) {
if (schedulerFuture != null) {
schedulerFuture.cancel(true);
}
this.delayInterval += delay;
schedulerFuture = taskScheduler.schedule(() -> { }, this);
}
@Override
public void delay(Long delay) {
if (schedulerFuture != null) {
schedulerFuture.cancel(true);
}
this.delayInterval = delay;
schedulerFuture = taskScheduler.schedule(() -> { }, this);
}
@Override
public Date nextExecutionTime(TriggerContext triggerContext) {
Date lastTime = triggerContext.lastActualExecutionTime();
return (lastTime == null) ? new Date() : new Date(lastTime.getTime() + delayInterval);
}
}

3. Now we can write configuration.



@Configuration
public class DynamicSchedulerConfig {
@Bean
public DynamicSchedule getDinamicScheduler() {
ThreadPoolTaskScheduler threadPoolTaskScheduler = new ThreadPoolTaskScheduler();
threadPoolTaskScheduler.setPoolSize(1);
threadPoolTaskScheduler.initialize();
return new DynamicSchedule(threadPoolTaskScheduler);
}
}


In this example we just choose ThreadPoolTaskScheduler that is child ofTaskScheduler interface.


4. So what is the next? Let's see how to use our scheduler. Everything is simple:



@Autowired
private DynamicSchedule dynamicSchedule;
@Scheduled(fixedDelay=5000)
public void change() {
dynamicSchedule.increaseDelay(1000);
}
That's it!

Goodbye!
Have good day!

No comments:

Post a Comment