javaspringspring-bootscheduled-tasks

Call a method after Spring Boot app starts


I have a Java Spring Boot application which has a Scheduler which calls a async task from a Service The task takes a few minutes (usually 3-5mins) to complete.

The same async method from the Service can also be called trough a UI Application, by calling the API from the Spring Boot Controller.

Code:

Scheduler

@Component
public class ScheduledTasks {
  @Autowired
  private MyService myService;

  @Scheduled(cron = "0 0 */1 * * ?")
  public void scheduleAsyncTask() {
    myService.doAsync();
  }
}

Service

@Service
public class MyService {
  @Async("threadTaskExecutor")
  public void doAsync() {
    //Do Stuff
  }
}

Controller

@CrossOrigin
@RestController
@RequestMapping("/mysrv")
public class MyController {
  @Autowired
  private MyService myService;

  @CrossOrigin
  @RequestMapping(value = "/", method = RequestMethod.POST)
  public void postAsyncUpdate() {
    myService.doAsync();
  }
}

The scheduler runs the async task every hour, but a user can also run it manually from the UI.

But, I do not want the async method to run again if it is already in the middle of execution.

In order to do that, I have created a table in DB which contains a flag which goes on when the method is running and then it is turned off after the method completes.

Something like this in my service class:

@Autowired
private MyDbRepo myDbRepo;

@Async("threadTaskExecutor")
public void doAsync() {
  if (!myDbRepo.isRunning()) {
    myDbRepo.setIsRunning(true);
    //Do Stuff
    myDbRepo.setIsRunning(false);
  } else {
    LOG.info("The Async task is already running");
  }
}

Now, the problem is that the flag sometimes gets stuck due to various reasons (app restarting, some other application error etc.)

So, I want to reset the flag in DB each time the spring boot application is deployed and whenever is restarts.

How can I do that? Is there some way to run a method just after the Spring Boot Application starts, from where I can call a method from my Repo to un set the flags in the database?


Solution

  • Check for the @PostConstruct for e.g here https://www.baeldung.com/running-setup-logic-on-startup-in-spring

    import jakarta.annotation.PostConstruct;
    import org.springframework.stereotype.Component;
    
    @Component
    public class ExampleBean {
    
        // 1. The constructor is called first.
        public ExampleBean() {
            System.out.println("STEP 1: Bean constructor has been called.");
        }
    
        // 2. This method runs AFTER the constructor and dependency injection are complete.
        @PostConstruct
        public void init() {
            System.out.println("STEP 2: The @PostConstruct init() method has been called.");
        }
    }