在 Spring 框架中,@Scheduled
注解通常用于创建重复执行的定时任务。要实现一个仅执行一次且在一分钟后执行的定时任务,可以结合使用 @PostConstruct
和 java.util.Timer
。@PostConstruct
注解确保在 Spring 容器初始化后立即执行方法,而 java.util.Timer
可以用来安排定时任务。
下面是一个示例代码,演示如何在一分钟后执行一个只会执行一次的任务:
import org.springframework.stereotype.Component;
import javax.annotation.PostConstruct;
import java.util.Timer;
import java.util.TimerTask;
@Component
public class MyTask {
@PostConstruct
public void init() {
Timer timer = new Timer();
TimerTask task = new TimerTask() {
@Override
public void run() {
execute();
}
};
long delay = 60 * 1000; // 一分钟后执行,单位是毫秒
timer.schedule(task, delay);
}
public void execute() {
System.out.println("定时任务执行时间:" + System.currentTimeMillis());
}
}