Spring Boot Scheduler | Random trigger failures

Viewed 13

I have a query related to spring scheduler.

I have implemented scheduler as below which just prints current timestamp every 5 seconds. This used to work perfectly fine when the project was on springboot version 3.6.3. On springboot version update to 3.7.1 this implementation randomly stops after first trigger.

I'm trying to add a handle to start scheduler when it stops. Have tried with postProcessBeforeDestruction and postProcessAfterInitialization methods, which is not helping.

Any help would be much appreciated.

Scheduler class is as below

import java.util.Calendar;
import java.util.Date;
import java.util.GregorianCalendar;
import java.util.concurrent.Executor;
import java.util.concurrent.ExecutorService;
import java.util.concurrent.Executors;

import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.scheduling.annotation.EnableScheduling;
import org.springframework.scheduling.annotation.SchedulingConfigurer;
import org.springframework.scheduling.config.ScheduledTaskRegistrar;

@Configuration
@EnableScheduling
public class Test implements SchedulingConfigurer {

    @Bean(destroyMethod = "shutdown")
    public Executor taskExecutor() {
        return Executors.newScheduledThreadPool(1);
    }

    @Override
    public void configureTasks(ScheduledTaskRegistrar taskRegistrar) {
        taskRegistrar.setScheduler(taskExecutor());

        taskRegistrar.addTriggerTask(() -> {
            System.out.println(":::Inside Runnable Method:::");
            ExecutorService e = Executors.newCachedThreadPool();
            e.submit(new BatchRunner(1L));
            e.shutdown();
        }, triggerContext -> {
            System.out.println(":::Inside Trigger:::");
            Calendar nextExecutionTime = new GregorianCalendar();
            Date lastActualExecutionTime = triggerContext.lastActualExecutionTime();
            nextExecutionTime.setTime(lastActualExecutionTime != null ? lastActualExecutionTime : new Date());
            String schedulerTime = "5";
            nextExecutionTime.add(Calendar.SECOND, null != schedulerTime ? Integer.parseInt(schedulerTime) : 0);
            return nextExecutionTime.getTime();
        });
    }

    private class BatchRunner implements Runnable {
        private long id;
        public BatchRunner(long id) {
            this.id = id;
        }

        @Override
        public void run() {
            System.out.println();
            System.out.println("::::TIME:::: "+  new Date());
        }
    }

}

Logs

:::Inside Runnable Method:::
:::Inside Trigger:::

::::TIME:::: Thu Sep 15 17:04:09 

:::Inside Runnable Method:::
:::Inside Trigger:::

::::TIME:::: Thu Sep 15 17:04:14 
0 Answers
Related