Reputation: 618
I have a scheduler, which triggers at a fixed delay of 5secs. I am planning to have more than one schedulers, but for now, let's stick to just one scheduler.
Requirement: Based on business condition scheduler's fixedDelay should be changed (e.g, default fixedDelay is 5secs, but it can be 6, 8, 10secs, based on condition).
In order to achieve this, I am trying to modify the fixedDelay. But it's not working for me.
Interface, with delay methods
public abstract class DynamicSchedule{
/**
* Delays scheduler
* @param milliseconds - the time to delay scheduler.
*/
abstract void delay(Long milliseconds);
/**
* Decreases delay period
* @param milliseconds - the time to decrease delay period.
*/
abstract void decreaseDelayInterval(Long milliseconds);
/**
* Increases delay period
* @param milliseconds - the time to increase dela period
*/
abstract void increaseDelayInterval(Long milliseconds);
}
Implementating Trigger interface that is located at org.springframework.scheduling in the spring-context project.
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);
}
}
configuration:
@Configuration
public class DynamicSchedulerConfig {
@Bean
public CustomDynamicSchedule getDinamicScheduler() {
ThreadPoolTaskScheduler threadPoolTaskScheduler = new ThreadPoolTaskScheduler();
threadPoolTaskScheduler.initialize();
return new CustomDynamicSchedule(threadPoolTaskScheduler);
}
}
Test class, to test the usage.
@EnableScheduling
@Component
public class TestSchedulerComponent {
@Autowired
private CustomDynamicSchedule dynamicSchedule;
@Scheduled(fixedDelay = 5000)
public void testMethod() {
dynamicSchedule.delay(1000l);
dynamicSchedule.increaseDelayInterval(9000l);
dynamicSchedule.decreaseDelayInterval(5000l);
}
}
I have tried to use https://stackoverflow.com/a/51333059/4770397 but this code is not working for me.
Scheduler is running at fixedDelay, there is no change in that.
Upvotes: 13
Views: 18748
Reputation: 39
Spring does not have direct support using a variable for Frequency of a scheduler. Writing a custom master scheduler (say scheduled to execute every second) to control the other schedules is a good option.
Upvotes: 0
Reputation: 10964
Using @Scheduled
will only allow to use static schedules. You can use properties to make the schedule configruable like this
@Scheduled(cron = "${yourConfiguration.cronExpression}")
// or
@Scheduled(fixedDelayString = "${yourConfiguration.fixedDelay}")
However the resulting schedule will be fixed once your spring context is initialized (the application is started).
To get fine grained control over a scheduled execution you need implement a custom Trigger
- similar to what you already did. Together with the to be executed task, this trigger can be registered by implementing SchedulingConfigurer
in your @Configuration
class using ScheduledTaskRegistrar.addTriggerTask
:
@Configuration
@EnableScheduling
public class AppConfig implements SchedulingConfigurer {
@Override
public void configureTasks(ScheduledTaskRegistrar taskRegistrar) {
taskRegistrar.setScheduler(taskScheduler());
taskRegistrar.addTriggerTask(() -> myTask().work(), myTrigger());
}
@Bean(destroyMethod="shutdown")
public Executor taskScheduler() {
return Executors.newScheduledThreadPool(42);
}
@Bean
public CustomDynamicSchedule myTrigger() {
new CustomDynamicSchedule();
}
@Bean
public MyTask myTask() {
return new MyTask();
}
}
But don't do any registration of a task in the CustomDynamicSchedule
just use it to compute the next execution time:
public class CustomDynamicSchedule extends DynamicSchedule implements Trigger {
private long delayInterval;
@Override
public synchronized void increaseDelayInterval(Long delay) {
this.delayInterval += delay;
}
@Override
public synchronized void decreaseDelayInterval(Long delay) {
this.delayInterval += delay;
}
@Override
public synchronized void delay(Long delay) {
this.delayInterval = delay;
}
@Override
public Date nextExecutionTime(TriggerContext triggerContext) {
Date lastTime = triggerContext.lastActualExecutionTime();
return (lastTime == null) ? new Date() : new Date(lastTime.getTime() + delayInterval);
}
}
But remember to make CustomDynamicSchedule
thread safe as it will be created as singleton by spring and might be accessed by multiple threads in parallel.
Upvotes: 12
Reputation: 9492
With annotation you can do it only by aproximation by finding a common denominator and poll it. I will show you later. If you want a real dynamic solution you can not use annotations but you can use programmatic configuration. The positive of this solution is that you can change the execution period even in runtime! Here is an example on how to do that:
public initializeDynamicScheduledTAsk (ThreadPoolTaskScheduler scheduler,Date start,long executionPeriod) {
scheduler.schedule(
new ScheduledTask(),
new Date(startTime),period
);
}
class ScheduledTask implements Runnable{
@Override
public void run() {
// my scheduled logic here
}
}
There is a way to cheat and actually do something with annotations. But you can do that only if precision is not important. What does it mean precision. If you know that you want to start it every 5 seconds but 100ms more or less is not important. If you know that you need to start every 5-6-8 or 10 seconds you can configure one job that is executing every second and check within one if statement how long has it passed since the previous execution. It is very lame, but it works :) as long as you don't need up to millisecond precision. Here is an example:
public class SemiDynamicScheduledService {
private Long lastExecution;
@Value(#{yourDynamicConfiguration})
private int executeEveryInMS
@Scheduled(fixedDelay=1000)
public semiDynamicScheduledMethod() {
if (System.currentTimeMS() - lastExecution>executeEveryInMS) {
lastExecution = System.currentTimeMS();
// put your processing logic here
}
}
}
I is a bit lame but will do the job for simple cases.
Upvotes: 1
Reputation: 916
Spring's @Scheduled
annotation does not provide this support.
This is my preferred implementation of a similar feature using a Queue-based solution which allows flexibility of timing and very robust implementation of this scheduler functionality.
cron
and a single-threaded executor service which is responsible for publishing messages to the Queue as per the cron. The task-cron
mappings are persisted in the database
and are initialized during the startup. Also, we have an API
exposed to update cron for a task at runtime.
We simply shut down the old scheduled executor service and create a one whenever we trigger a change in the cron via our API. Also, we update the same in the database.
There are various advantages to this approach. This decouples the scheduler from the schedule management task. Now, the scheduler can focus on business logic alone. Also, we can write as many schedulers as we want, all listening to the same queue and acting accordingly.
Upvotes: 1