Exit Spring Boot app when all timers are done

I am running a few TimerTasks from my Spring Boot application. The CommandLineRunner implementation is like below:

@SpringBootApplication
public class Main implements CommandLineRunner {

  private final Timer1 timer1;
  private final Timer2 timer2;

  static LocalDateTime startTime = LocalDateTime.now();

  public Main(Timer1 timer1, Timer2 timer2) {
    this.timer1 = timer1;
    this.timer2 = timer2;
  }

  public static void main(String[] args) {
    SpringApplication app = new SpringApplication(Main.class);
    app.setBannerMode(Banner.Mode.OFF);
    app.run(args);
  }

  @Override
  public void run(String... args) throws Exception {
    Timer t1 = new Timer();
    Timer t2 = new Timer();
    int tickTime = 10000;
    t1.scheduleAtFixedRate(this.timer1, 0, tickTime);
    t2.scheduleAtFixedRate(this.timer2, 5000, tickTime);
  }

}

The above successfully schedules both the TimerTasks. However in my timer tasks, I am checking the current time against Main.startTime to count the running minutes. If the minutes exceed a threshold, I am cancelling the tasks.

// Timer1.java
@Component
public class Timer1 extends GenericTimer {

  @Override
  public void run() {
    quitIfTimedOut();
  }

}

// Timer2.java
@Component
public class Timer2 extends GenericTimer {

  @Override
  public void run() {
    quitIfTimedOut();
  }

}

// GenericTimer.java
public abstract class GenericTimer extends TimerTask {

  protected void quitIfTimedOut() {
    LocalDateTime now = LocalDateTime.now();
    int timeoutThreshold = 1;
    long minutesSinceRunning = Main.startTime.until(now, ChronoUnit.MINUTES);

    if (minutesSinceRunning >= timeoutThreshold) {
      cancel();
    }
  }

}

So far, it correctly cancels the timer tasks as per the specified criteria. My question is, how to terminate the main thread if all the timer tasks are canceled?

Do I need to continuously watch for the tasks to be canceled in the Main.java and call SpringApplication.close( … ), or is there something more convenient and robust method available?

The best way i found to do is as you mentioned:

I inject the ApplicationContext and do something like the following to gracefully close the application:

int exit = SpringApplication.exit(this.applicationContext); // close gracefully before exit
System.exit(exit);

Spring closes all DB connections etc and then i force exit the application.