Reputation: 133
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
Upvotes: 3
Views: 2371
Reputation: 6969
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();
}
Upvotes: 9