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.
Asked
Active
Viewed 1,647 times
0
-
try multithreading with thread sleep as 2 seconds.. – Maximin Aug 15 '14 at 18:39
-
1This might be helpful http://www.java2s.com/Tutorial/Java/0280__SWT/Createtwooneshottimers2000ms.htm – Praneeth Peiris Aug 15 '14 at 18:48
-
A standard way to repeat a task in java can be done using java.util.Timer and java.util.TimerTask – Frederic Close Aug 15 '14 at 18:49
-
possible duplicate of [Java Timer vs ExecutorService?](http://stackoverflow.com/questions/409932/java-timer-vs-executorservice) – iwein Aug 15 '14 at 19:04
-
[This answer](http://stackoverflow.com/a/16111306) should be helpful. – Baz Aug 15 '14 at 19:21
1 Answers
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
-
-
1That sounds like it needs to run on the UI thread, so `Display.timerExec` is best. – greg-449 Aug 15 '14 at 19:04
-
-
You put it at the point where you want to run something 2 seconds later. – greg-449 Aug 15 '14 at 19:10
-
ok, I have to create a runnable variable? because eclipse give me an error – Rick Aug 15 '14 at 19:16
-
`timerExec` expects an instance of `Runnable` which you have to create containing the code you want to run. – greg-449 Aug 15 '14 at 19:19
-