gpt4 book ai didi

Java 定时器和 scheduleAtFixedRate + 系统挂起

转载 作者:塔克拉玛干 更新时间:2023-11-03 04:23:57 35 4
gpt4 key购买 nike

我正在开发一个 Java 程序并使用 Timer 对象每隔几分钟或几小时运行一次任务。这在正常操作中工作正常,但我在 Mac 上遇到了“ sleep 模式”的问题(可能在其他操作系统上,但我还没有尝试过)。

考虑这个代码示例:

//Setup the timer to fire the ping worker (every 3 minutes)
_PingTimer.scheduleAtFixedRate(new TimerTask(){
public void run(){
Program.PingThread = new PingWorker(Settings.Username, Settings.UserHash, true, true);
Program.PingThread.CheckOpenPort = true;
Program.SwingExecutor.execute(Program.PingThread);
}
}, 0, 180000);

在正常操作中,它会以足够的精度每 3 分钟触发一次(我不关心确切的秒数或其他任何东西)。这个问题是在计算机 sleep 几个小时左右之后,它似乎只是用积压的计时器请求来破坏系统。

它似乎在 sleep 期间同时运行所有错过的计时器,试图弥补丢失的时间。

有什么办法可以避免这种情况吗?我尝试使用 synchronized 和其他一些线程技术,但这只能确保它们不会同时运行。他们仍然继续一个接一个地运行,直到积压通过。

感谢您提供的任何帮助!

最佳答案

你看过API了吗? ?它清楚地说明了以下内容:

In fixed-rate execution, each execution is scheduled relative to the scheduled execution time of the initial execution. If an execution is delayed for any reason (such as garbage collection or other background activity), two or more executions will occur in rapid succession to "catch up." In the long run, the frequency of execution will be exactly the reciprocal of the specified period (assuming the system clock underlying Object.wait(long) is accurate).

这就是您应该考虑使用 ScheduledExecutorService 的原因之一.这link也可能有用。

关于Java 定时器和 scheduleAtFixedRate + 系统挂起,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/5568304/

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