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();
}
}
}
}
It is present under package org.springframework.boot. In startup process after the context is initialized, spring boot calls its run () method with command-line arguments provided to the application.
CommandLineRunner is a spring boot functional interface which is used to run code at application startup. It is present under package org.springframework.boot. In startup process after the context is initialized, spring boot calls its run () method with command-line arguments provided to the application.
Procrun is a set of applications that allow Windows users to wrap Java applications as Windows services. Such a service may be set to start automatically when the machine boots and will continue to run without any user being logged on. More details on starting Spring Boot applications under Unix may be found here.
We create a job your-app.conf to start our Spring Boot application: Now run “start your-app” and your service will start. Upstart offers many job configuration options, you can find most of them here.
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
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.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With