开发者

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.


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)


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);
0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜