Skip to content
Advertisement

How to have an asynchronous and non-concurrent scheduler in Spring?

I have in the main class that starts the app:

@SpringBootApplication
@EnableAsync
public class ExperianRequestBotApplication extends RefApplication {

    public ExperianRequestBotApplication() throws RefException {
        super();
    }

    public static void main(String[] args) throws RefException {
        try {
            new ExperianRequestBotApplication().start(args);
        } catch (Exception e) {
            System.out.println(" ------- OFFLINE ------- ");
            System.out.println("La aplicación no esta disponible por :" + e);
        }

    }
}

and a scheduler

@Component
public class ScheduledTaskSincronizarContactos {

    @Autowired
    private ExperianRequestBotService experianRequestBotService;

    private final static Logger LOG = LoggerFactory.getLogger(ScheduledTaskSincronizarContactos.class);

    // Método Shedule encargado de sincronizar los usuarios modificados con Experian 
    @Async
    @Scheduled(cron = "0 */15 * ? * *")
    public void SincronizarContactos() throws Exception {

I want to prevent the scheduler from being launched again if the internal process takes more than 15 minutes to start the task again.

I can’t find the way. I have tried implementing @DisallowConcurrentExecution with the quartz library but it is still concurrent.

Any ideas?

Advertisement

Answer

I’ve faced a similar issue with concurrency while using spring scheduling. We had a lot of jobs all running on the same service and interfering with each other. We switched to using Quartz Scheduling – felt simpler than the Spring multithreaded scheduler with a bunch of other features that we wanted. This repo was really helpful. https://gitlab.com/johnjvester/jpa-spec-with-quartz/-/blob/master/src/main/java/com/gitlab/johnjvester/jpaspec/config/QuartzConfig.java

Quartz scheduling also has the advantage of being persistent – when it starts up, it will trigger all the missed jobs. One can also alter cron statements programmatically. This might be an overkill for your use case but it is worth a look. 🙂 Also, what Wasif said – use delays to define when the job should be run vs a cron expression and you’re guaranteed a win even with Spring!

User contributions licensed under: CC BY-SA
2 People found this is helpful
Advertisement