I am using spring scheduler and have the requirement to print the log inside the spring scheduler after every 1 minute. Below is the code & configuration for the spring scheduler.
@Slf4j
@EnableScheduling
@Component
@RequiredArgsConstructor
public class EventConsumer {
private AtomicReference<LocalDateTime> lastLoggedTime = new AtomicReference<>(LocalDateTime.now());;
public LocalDateTime getLastLoggedTime() {
return lastLoggedTime.get();
}
public void setLastLoggedTime(LocalDateTime lastLoggedTime) {
if(lastLoggedTime.isAfter(this.lastLoggedTime.get())) {
this.lastLoggedTime.set(lastLoggedTime);
}
else{
log.info("Time trying to update is in past EventConsumer");
}
}
@Scheduled(initialDelay = 5, fixedDelayString = "30000")
public void pollAxonMessages() {
LocalDateTime currentTime = LocalDateTime.now();
if (isLogginEnabled(getLastLoggedTime(),60,currentTime,"Event Consumer")) {
log.info("Started polling ");
setLastLoggedTime(currentTime);
}
}
public boolean isLogginEnabled(LocalDateTime lastLoggedInTime,
Integer loggingInterval,
LocalDateTime currentDateTime,
String consumerName){
log.info("LocalDateTime : {} , loggingInterval : {} , currentDateTime :{} consumerName: {}", lastLoggedInTime, loggingInterval, currentDateTime, consumerName);
return lastLoggedInTime.plusSeconds(loggingInterval).isBefore(currentDateTime);
}
}
YAML file configuration for spring scheduler.
spring:
task:
scheduling:
pool:
size: 8
I am using the spring boot version 2.4.1 and deploying the application in PCF cloud Foundary. Issue is that I can see scheduling-2 & scheduling-4 threads running inside the event consumer and when one of the thread(scheduling-2) is updating the lastLoggedTime the other one is still not receiving the update and using the old lastLoggedTime value causing the same statement to print twice with in 60 seconds rather than once.
Can you please let me know what did I missed in the above code causing this issue?