运行 进程在后台使用 spring 启动
run process in background using spring boot
如何使用 Spring 启动 运行 一些后台进程?这是我需要的示例:
@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();
}
}
}
}
您可以使用异步行为。当您调用该方法时,当前线程确实在等待它完成。
像这样创建一个可配置的class。
@Configuration
@EnableAsync
public class AsyncConfiguration {
@Bean(name = "threadPoolTaskExecutor")
public Executor threadPoolTaskExecutor() {
return new ThreadPoolTaskExecutor();
}
}
然后在一个方法中使用:
@Async("threadPoolTaskExecutor")
public void someAsyncMethod(...) {}
查看 spring documentation 了解更多信息
您可以只使用@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.
如何使用 Spring 启动 运行 一些后台进程?这是我需要的示例:
@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();
}
}
}
}
您可以使用异步行为。当您调用该方法时,当前线程确实在等待它完成。
像这样创建一个可配置的class。
@Configuration
@EnableAsync
public class AsyncConfiguration {
@Bean(name = "threadPoolTaskExecutor")
public Executor threadPoolTaskExecutor() {
return new ThreadPoolTaskExecutor();
}
}
然后在一个方法中使用:
@Async("threadPoolTaskExecutor")
public void someAsyncMethod(...) {}
查看 spring documentation 了解更多信息
您可以只使用@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.