我尝试每小时执行一次代码
这适用于可以与服务器一起运行的 applicationRunner 中的 java 启动。
@Component
public class TestApplicationRunner implements ApplicationRunner {
// some Autowired
@Override
public void run(ApplicationArguments args) throws Exception {
TimerTask repeatedTask = new TimerTask() {
@Override
public void run() {
System.out.println("Task performed on " + new Date()); //now
//Some code that updates the database
}
};
Timer timer = new Timer();
Calendar date = Calendar.getInstance();
LocalDateTime nextHour = LocalDateTime.now().plusHours(1).truncatedTo(ChronoUnit.HOURS);
long result = LocalDateTime.now().until(nextHour, ChronoUnit.MILLIS);
System.out.println(date.getTime());
long period = 1000L * 60L * 60L;
timer.scheduleAtFixedRate(repeatedTask, result, period);
}
}
如果我在12:34运行这段代码,结果是
Task performed on 13 : 00
Task performed on 14 : 00
Task performed on 14 : 00
Task performed on 15 : 00
Task performed on 15 : 00
Task performed on 15 : 00
Task performed on 16 : 00
Task performed on 16 : 00
Task performed on 16 : 00
Task performed on 16 : 00
.....
我想收到
Task performed on 13 : 00
Task performed on 14 : 00
Task performed on 15 : 00
Task performed on 16 : 00
Task performed on 17 : 00
.....
我认为线程不止一个,但我不明白为什么他们有多个线程。我添加我的代码。谢谢你的帮助