Ray*_* En 5 java spring-boot workmanagertaskexecutor
如何使用 Spring Boot 在后台运行某些进程?这是我需要的一个例子:
@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();
}
}
}
}
Run Code Online (Sandbox Code Playgroud)
kim*_*y82 10
您可以使用异步行为。当您调用该方法并且当前线程确实等待它完成时。
像这样创建一个可配置的类。
@Configuration
@EnableAsync
public class AsyncConfiguration {
@Bean(name = "threadPoolTaskExecutor")
public Executor threadPoolTaskExecutor() {
return new ThreadPoolTaskExecutor();
}
}
Run Code Online (Sandbox Code Playgroud)
然后在一个方法中使用:
@Async("threadPoolTaskExecutor")
public void someAsyncMethod(...) {}
Run Code Online (Sandbox Code Playgroud)
查看spring 文档以获取更多信息
您可以只使用@Scheduled-Annotation。
@Scheduled(fixedRate = 5000)
public void reportCurrentTime() {
log.info("The time is now " + System.currentTimeMillis()));
}
Run Code Online (Sandbox Code Playgroud)
https://spring.io/guides/gs/scheduling-tasks/:
Scheduled 注释定义特定方法何时运行。注意:此示例使用 fixedRate,它指定从每次调用的开始时间开始测量的方法调用之间的间隔。
| 归档时间: |
|
| 查看次数: |
13621 次 |
| 最近记录: |