假设有一个 Spring boot Web 应用程序,其中 2 个类映射为 @Controller 和 @Service。服务被注入到控制器的字段中。我需要我的服务每秒运行一次任务来更新一些外部数据。这段代码有问题吗?
@Component
public class MyService implements Runnable{
public MyService() {
new Thread(this).start();
}
@Override
public void run() {
while (true) {
try {
Thread.sleep(1000);
// operations here
} catch (InterruptedException e) {
e.printStackTrace();
}
}
}
}
尽管有很多方法可以使用作业或 Spring 任务调度器创建任务,但下面是一种简单的方法。
下面的任务将每秒运行一次。
Timer timer = new Timer();
timer.schedule(new TimerTask() {
@Override
public void run() {
System.out.println("hello");
}
}, 0, 1000); // o is delay time after which it starts, 1000 is time interval
或者你可能想参考这里来实现 Spring 任务调度器。