How to keep Spring context open?

Viewed 102

I have a minimal Spring (not Spring Boot) application which has a scheduled method, but the context is closed before the task is triggered.

@Configuration
@EnableScheduling
public class Main {
    @Bean
    public TaskScheduler scheduler() {
        return new ThreadPoolTaskScheduler();
    }

    @Scheduled(cron = "0 * * * * *")
    public void run() {
        System.out.println("tick"); // Never happens
    }

    public static void main(final String... args) {
        try (GenericApplicationContext ctx = new AnnotationConfigApplicationContext(Main.class)) {
            ctx.start();
        }
    }
}

How should I prevent context from closing?

1 Answers

Spring context is just metadata and it is really not good practice to relate on it. Have you tried declaring the main method in a standard way?

This works fine for me:

@EnableScheduling
@Configuration
public class DemoApplication {

    @Scheduled(cron = "0 * * * * *")
    public void run(){
        System.out.println("tick");
    }

    public static void main(String[] args) {
        SpringApplication.run(DemoApplication.class, args);
    }

}
Related