0

Hi guys I have to create a timer that every 2 seconds repeat a part of my code, can you tell me the code? I don't need the graphic on this timer.

Rick
  • 63
  • 1
  • 10

1 Answers1

1

You can use java.util.concurrent.ScheduledExecutorService:

ScheduledExecutorService scheduler = Executors.newScheduledThreadPool(1);

scheduler.scheduleAtFixedRate(runnable, 2, 2, TimeUtil.SECONDS);

Or you can use java.util.Timer.

Or with SWT you can use:

Display.getDefault().timerExec(2000, runnable);

which guarantees that the runnable will be executed on the user interface thread. With timerExec you have to reschedule the runnable each time it runs.

runnable is an instance of the Runnable class containing the code you want to execute, for example in Java 8 you can use:

Runnable runnable = () ->
  {
    browser.refresh();

    Display.getDefault().timerExec(2000, this);
  };

for Java 7 and earlier use:

Runnable runnable = new Runnable()
 {
   public void run()
   {
     browser.refresh();

     Display.getDefault().timerExec(2000, this);
   }
 };
greg-449
  • 109,219
  • 232
  • 102
  • 145