Start thread at springboot application

Don’t mess around with threads yourself. Spring (and also plain Java) has a nice abstraction for that.

First create a bean of the type TaskExecutor in your configuration

@Bean
public TaskExecutor taskExecutor() {
    return new SimpleAsyncTaskExecutor(); // Or use another one of your liking
}

Then create a CommandLineRunner (although an ApplicationListener<ContextRefreshedEvent> would also work) to schedule your task.

@Bean
public CommandLineRunner schedulingRunner(TaskExecutor executor) {
    return new CommandLineRunner() {
        public void run(String... args) throws Exception {
            executor.execute(new SimularProfesor());
        }
    }
}

You could of course make also your own class managed by spring.

Advantage of this is that Spring will also cleanup the threads for you and you don’t have to think about it yourself. I used a CommandLineRunner here because that will execute after all beans have bean initialized.

Leave a Comment