Java Thread.sleep waking up “much” earlier than the scheduled time

老子叫甜甜 提交于 2020-01-23 12:22:35

问题


I have a requirement of writing a daemon which initiates number of threads that wakes up at different times. The daemon is written in Java using commons apache library and is run on a Linux machine (Fedora 13 ). One thread wakes up everyday to perform task A which happens as scheduled. But there is another thread which is scheduled to wake up every Monday at 6 am to perform some task which does not happen as scheduled. The problem is that this thread wakes up much before the actual scheduled time. It runs 2 days after the completion of the previous run though it should run only after a week. The waiting time is calculated correctly using our own timer class and because this reuses existing code i do not see a problem in this.

What could be the problem here?

Thanks


回答1:


Thread.sleep() doesn't make any guarantees, and it might wake up earlier than expected. you should always use it in the loop:

long curTime = System.currentTimeMillis();

while (wakeUpTime - curTime > 0) {
  try {
    Thread.sleep(wakeUpTime - curTime);
  } catch (InterruptedException ex) { }
  curTime = System.currentTimeMillis();
}


来源:https://stackoverflow.com/questions/5045420/java-thread-sleep-waking-up-much-earlier-than-the-scheduled-time

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!