guys i have written a code which has to be executed after every 1 hour...i have used do while loops for that..part of code is as following;
do
{开发者_开发技巧
time1=d.get(Calendar.HOUR_OF_DAY);
month1=d.get(Calendar.MONTH);
if(month1-m1==1)
break;
}
while (time1-time!=1);
//where m1 and time are previously calculated values
Is there any another more efficient method of performing above function in Windows...the above code has made my computer very slow.
try {
Thread.sleep(1000 * 60 * 60);
} catch (InterruptedException ex) {}
Your really burning cpu with the loop. Try using a Timer & TimerTask, http://www.javapractices.com/topic/TopicAction.do?Id=54
You don't appear to be updating the d
inside the loop, so it will never change. If you are going to busy wait for the hour to change, I suggest to poll the time inside the loop.
Calendar using daylight savings. If time is wound back an hour, would you expect it to wait for two hours?
You appear to be checking the month change in case the application is suspended. ?guessing? However, I would expect checking the DAY might more useful than checking the month. e.g. if I hibernate for a day, the month might not change.
If you want to wait an hour, using sleep is a simple approach but if you want to have a task which is performed every hour, I would suggest you use a ScheduledExecutorService
ScheduledExecutorService executor =
executor.scheduleAtFixedRate(task, 0, 1, TimeUnit.HOUR); // runs task every hour
This same scheduler can be used to run many different types of tasks using the same thread(s)
If you are on Windows, use Scheduled Tasks:
http://support.microsoft.com/kb/226795/en-us
On Unix use cron:
http://en.wikipedia.org/wiki/Cron
Hardly surprising that a constant loop is slowing down your computer. If you only want it to run once, on the hour, with some break conditions, you'd be better off using the Timer and TimerTask classes.
You could do this also with Windows scheduled Tasks
Use java timer for your task.See here
精彩评论