[英]run process in background using spring boot
How can I run some process in background using Spring Boot? 如何使用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();
}
}
}
}
You could just use the @Scheduled-Annotation. 您可以只使用@ Scheduled-Annotation。
@Scheduled(fixedRate = 5000)
public void reportCurrentTime() {
log.info("The time is now " + System.currentTimeMillis()));
}
https://spring.io/guides/gs/scheduling-tasks/ : https://spring.io/guides/gs/scheduling-tasks/ :
The Scheduled annotation defines when a particular method runs.
Scheduled注释定义何时运行特定方法。 NOTE: This example uses fixedRate, which specifies the interval between method invocations measured from the start time of each invocation.
注意:此示例使用fixedRate,它指定从每次调用的开始时间开始测量的方法调用之间的间隔。
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 看看spring文档以获取更多信息
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.