Reputation: 83
How can I run some process in background using Spring Boot? This is an example of what I need:
@SpringBootApplication
public class SpringMySqlApplication {
@Autowired
AppUsersRepo appRepo;
public static void main(String[] args) {
SpringApplication.run(SpringMySqlApplication.class, args);
while (true) {
Date date = new Date();
System.out.println(date.toString());
try {
TimeUnit.SECONDS.sleep(3);
} catch (InterruptedException e) {
e.printStackTrace();
}
}
}
}
Upvotes: 7
Views: 24822
Reputation: 320
You could just use the @Scheduled-Annotation.
@Scheduled(fixedRate = 5000)
public void reportCurrentTime() {
log.info("The time is now " + System.currentTimeMillis()));
}
https://spring.io/guides/gs/scheduling-tasks/:
The Scheduled annotation defines when a particular method runs. NOTE: This example uses fixedRate, which specifies the interval between method invocations measured from the start time of each invocation.
Upvotes: 11
Reputation: 4465
You can use Async behaviour. When you call the method and the current thread does wait for it to be finished.
Create a configurable class like this.
@Configuration
@EnableAsync
public class AsyncConfiguration {
@Bean(name = "threadPoolTaskExecutor")
public Executor threadPoolTaskExecutor() {
return new ThreadPoolTaskExecutor();
}
}
And then used in a method:
@Async("threadPoolTaskExecutor")
public void someAsyncMethod(...) {}
Have a look at spring documentation for more info
Upvotes: 12