4
My application has a scheduled method to run every 5 minutes with the @Scheduled
of Spring, but I would like to rise more than one instance of implementation and that this task should not be carried out more than once independent of the number of instances.
Main Class
@SpringBootApplication
public class SchedulingApplication {
public static void main(String[] args) {
System.setProperty("spring.application.name", "scheduling-application");
SpringApplication.run(SchedulingApplication.class, args);
}
}
Scheduled Task
@Scheduled(cron = "0 * * * * *")
public void searchAndSend() {
// FAZ UMA BUSCA E MANDA PRA FILA
}
As it stands, if I go up two instances the search and send task to the queue will be executed twice a minute. If I go up three, it will be three per minute. How do I make this task run only once independent of the number of instances?
You can use the strategy of setting a property at the startup of your instance, so only one of them has the property to activate the Schedule of your activity. However, the Schedule mechanism should be done manually.
– nullptr
If you need help I can help with the implementation
– nullptr
Interesting. Can we consider this a gambiarra?! Hahahaha
– Gustavo
I believe not, even because the property will be set the same
spring.application.name
, but when initializing the jar or the server will inform on the boot parameters-Dspring.application.name=xpto -Dx.application.scheduler=true
for example, this already eliminates the first line of your method– nullptr
Based on the second property, Voce configures (or not) the Scheduler manually
– nullptr
managed to make?
– nullptr
I did using a solution called Shedlock
– Gustavo
Got it, actually the solution then got a little different from the question, you keep all instances running the Scheduler always, but, just one at a time.
– nullptr
The function with Scheduler exists in all instances. Which instance will perform the function does not matter, as long as it runs only once. Send the email only once for example.
– Gustavo