I'm using @Scheduled and @Async annotation of Spring.
My purpose
To schedule a sync method - which runs a for loop and this loop will run an async method, so the next value in the loop doesn't need to wait until the method is finished.
See my code below:
/**
* Explanation: Scheduling async task for getting new hired candidates from the Lumesse Queue and saving the received data.
*/
@LoggableDebug
@Scheduled(fixedRateString = "${scheduler.insertCandidateFromQueueInDB.fixedRate}")
public void insertNewHiredCandidateFromQueueInDbScheduler() {
for(EnvironmentContext environmentContext: context) {
if(environmentContext.isActive()) {
environmentAsyncHandlerInsertNewHiredCandidateFromQueueInDb(environmentContext);
}
}
}
/**
* @param environmentContext
* Explanation: Async task for getting new hired candidates from the Lumesse Queue and saving the received data.
*/
@LoggableDebug
@Async
public void environmentAsyncHandlerInsertNewHiredCandidateFromQueueInDb(EnvironmentContext environmentContext) {
CandidateLumesse candidateLumesse;
candidateLumesse = lumesseConnectorService.getNewHiredCandidateDataFromQueue(environmentContext);
}
Problem:
My async method does't run on different tasks. It only works when I put the @Async annotation also on my scheduled method. But then my scheduled method will runs asyncronuos to and that's not what I want. The scheduled method needs to run synchronous but the called method in the for loop needs to run asynchronous.
Tries
I tried a workaround like this one:
Spring @Async method call inside @Scheduled method
-> putting my async methods in another class. Like this:
@LoggableDebug
@Scheduled(fixedRateString = "${scheduler.insertCandidateFromQueueInDB.fixedRate}")
public void insertNewHiredCandidateFromQueueInDbScheduler() {
for(EnvironmentContext environmentContext: context) {
if(environmentContext.isActive()) {
asyncServiceExecutor.environmentAsyncHandlerInsertNewHiredCandidateFromQueueInDb(environmentContext);
}
}
}
problem now is that my scheduled task get executed twice ...
Update
I did some more logging and my object only gets created once:
2018-02-06 13:17:19.053 WARN 13144 --- [ main]
c.d.l.c.s.LumesseConnectorScheduler : #### SCHEDULER CLASS CONSTRUCTOR
My fixedRate is 3000 -> 3 seconds Someone requested "increase it to 30 sec to see the flow", but still it is executing twice: So after 3 or 30 seconds or whatever the fixed rate has been set to, it will execute it twice instead of once..
2018-02-06 13:17:26.388 WARN 13144 --- [pool-7-thread-1]
c.d.l.c.s.LumesseConnectorScheduler : #### START SCHEDULING
2018-02-06 13:17:26.397 WARN 13144 --- [pool-7-thread-1]
c.d.l.c.s.LumesseConnectorScheduler : #### START SCHEDULING
-> Time between the two executions is just some very low miliseconds .. I just don't understand ..
Any thoughts ?