开发者

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

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 calcul开发者_C百科ated 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


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();
}
0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜