gpt4 book ai didi

java - 使用计时器进行 ScheduleAtFixedRate

转载 作者:行者123 更新时间:2023-12-02 09:39:42 27 4
gpt4 key购买 nike

我尝试每小时执行一次代码

这是针对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
.....

我认为线程不止一个,但我不明白为什么他们有多个线程。我添加我的代码。谢谢你的帮助

最佳答案

首先:java.util.Timer已经过时了。建议使用java.util.concurrent.ScheduledThreadPoolExecutor相反:

Java 5.0 introduced the java.util.concurrent package and one of the concurrency utilities therein is the ScheduledThreadPoolExecutor which is a thread pool for repeatedly executing tasks at a given rate or delay. It is effectively a more versatile replacement for the Timer/TimerTask combination, as it allows multiple service threads, accepts various time units, and doesn't require subclassing TimerTask (just implement Runnable). Configuring ScheduledThreadPoolExecutor with one thread makes it equivalent to Timer.

除此之外,在我看来,您的问题不在于日程安排。你的代码看起来是正确的。我的猜测是您的 TestApplicationRunner 启动了多次,因此创建了多个计时器。

关于java - 使用计时器进行 ScheduleAtFixedRate,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/57195526/

27 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com