• Post Reply Bookmark Topic Watch Topic
  • New Topic

Current Hour  RSS feed

 
kri shan
Ranch Hand
Posts: 1489
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
GregorainCalendar cal = new GregorainCalendar();
cal.get(Calendar.HOUR_OF_DAY);
I am getting current hour of the day thru this.
But whenever current hour changed, i want to do some specific operation...How can i monitor whether current hour is changed ?
 
K Riaz
Ranch Hand
Posts: 375
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
I know its not elegant, but why not get the hour, store it in a temp variable, put the thread to sleep for x amount of seconds, wake up, if current hour is not what is in the temp variable, then you know its changed.

You could go further and take the thread to sleep using the number of seconds left until the current hour will end. So if its quarter to five, then sleep for 15 minutes. This will avoid excessive looping and CPU usage.
 
Chengwei Lee
Ranch Hand
Posts: 884
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
You might wish to consider the java.util.Timer & java.util.TimerTask classes. What you could do is to instantiate a Timer object & have it schedule a TimerTask object at every hour.

You could easily find out the current system time & obtain the time difference to the next hour (in milliseconds). Then all you have to do would be to invoke the scheduleAtFixedRate method. You could specify when the first task starts (by using the time difference to the next hour) as well as in what interval it should be repeated. Not forgeting to tell it what task to perform.

You'll need to extend the abstract class TimerTask & override its run method to perform that specific task you'd in mind. To decouple your task from the concrete class of TimerTask, you could write your task in a separate class & use it inside the run method.

For more information, please refer to the Java API.

HTH.
 
It is sorta covered in the JavaRanch Style Guide.
  • Post Reply Bookmark Topic Watch Topic
  • New Topic
Boost this thread!