views:

298

answers:

3

Hi Everyone,

I have used java.util.Timer to schedule TimerTask to be run every 2 hours .

But how do I schedule a task to run say everynight at 2 am ?

This might be something easy, I am just overlooking something I guess.

Thanks in Advance

+2  A: 

You could use the Quartz scheduling system with a CronTrigger.

eljenso
+1  A: 

Call

timer.scheduleAtFixedRate(task, twoAmDate, twentyFourHoursInMillis )

on java.util.Timer

Mike Q
Yes, see http://java.sun.com/javase/6/docs/api/java/util/Timer.html#scheduleAtFixedRate(java.util.TimerTask, java.util.Date, long)
Adam Goode
A: 

You can make your own Thread to do this.
Use something like:

boolean todayExecuted = false;
while (true)
{
   Date now = new Date();
   if (now.getHours() == 2)
   {
      if (!todayExecuted)
      {
          todayExecuted = true;
          doTask(); // The call to the method you want to execute at 2 am
      }
   }
   if (now.getHours() == 0)
   {
       todayExecuted = false;
   }
   try { Thread.sleep(216000000L); } catch(Exception e) {} // Wait 1 hour
}
Martijn Courteaux
Using Thread directly is no longer really recommended, as java.util.concurrent provides a much nicer and higher level interface. Also, sleeping for 1 hour (or any amount of time) isn't the best way to assure a precise wakeup time.
Adam Goode