Bitmap
Bitmap

Reputation: 12538

Execute Java Timer at every 2 hours

I have a timer routine I want to execute every two hours. But my logic below seem to execute too early than expected. Does anyone know what I am doing wrong?

         (new Timer()).scheduleAtFixedRate(new TimerTask()
          {

            @Override
            public void run()
            {

              try
              {                  
               //TODO: Perform routine.
              }
              catch (Exception ex)
              {
                try
                {
                  throw ex;
                }
                catch (Exception e)
                {

                }
              }
            }

          }, 0, (1000 * 60 * 120));

Thanks.

Upvotes: 1

Views: 5170

Answers (2)

DNA
DNA

Reputation: 42586

According to the javadoc, your code should trigger the routine immediately (initial delay of zero), then after every 2 hours (period of 120 minutes).

scheduleAtFixedRate(TimerTask task, long delay, long period)

Schedules the specified task for repeated fixed-rate execution, beginning after the specified delay.

If you want the first triggering after 2 hours then do

long interval = 1000 * 60 * 120;
scheduleAtFixedRate(task, interval, interval)

Upvotes: 5

mre
mre

Reputation: 44240

Whenever possible, use the Executors framework instead of a Timer.

Executors.newSingleThreadScheduledExecutor().scheduleAtFixedRate(new Runnable(){
    @Override
    public void run()
    {
        // do stuff
    }}, 0, 2, TimeUnit.HOURS);

Upvotes: 3

Related Questions