Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Spring Boot Scheduler fixedDelay and cron

I'm running a spring boot scheduled process that takes 5-10 seconds to complete. After it completes, 60 seconds elapse before the process begins again (Note that I'm not using fixedRate):

@Scheduled(fixedDelay=60_000)

Now, I want to limit it to run every minute Mon-Fri 9am to 5pm. I can accomplish this with

@Scheduled(cron="0 * 9-16 ? * MON-FRI")

Problem here is that this acts similar to fixedRate - the process triggers EVERY 60 seconds regardless of the amount of time it took to complete the previous run...

Any way to to combine the two techniques?

like image 449
Tom D Avatar asked Nov 16 '25 11:11

Tom D


1 Answers

it worked for me like this

I created a bean that returns a specific task executor and allowed only 1 thread.

@Configuration
@EnableAsync
public class AsyncConfig implements AsyncConfigurer {

    @Bean(name = "movProcTPTE")
    public TaskExecutor movProcessualThreadPoolTaskExecutor() {
        ThreadPoolTaskExecutor exec = new ThreadPoolTaskExecutor();
        exec.setMaxPoolSize(1);
        exec.initialize();
        return exec;
    }
}

In my service, I injected my task executor and wrapped my logic with it, so even though my schedule runs every minute, my logic will only run when the task executor is free.

@Service
@EnableScheduling
public class ScheduledService {

    @Autowired
    private ReportDataService reportDataService;

    @Autowired
    private AsyncService async;

    @Autowired
    @Qualifier("movProcTPTE")
    private TaskExecutor movProcTaskExecutor;

    @Scheduled(cron = "0 * * 1-7 * SAT,SUN")
    public void agendamentoImportacaoMovProcessual(){
        movProcTaskExecutor.execute(
                () -> {
                    reportDataService.importDataFromSaj();
                }
        );

    }

}
like image 136
André Rodrigues de Sousa Avatar answered Nov 19 '25 09:11

André Rodrigues de Sousa