First, your Thread
based idiom will not be scheduled at a fixed speed without an infinite loop.
This drawback too: you probably want to set some condition to exit the loop.
You also need to catch InterruptedException
when calling static Thread.sleep
.
Another popular idiom for scheduled execution is the ScheduledExecutorService
.
Find the following 3 options:
Timer
// says "foo" every half second Timer t = new Timer(); t.scheduleAtFixedRate(new TimerTask() { @Override public void run() { System.out.println("foo"); } }, 0, 500);
In a fixed-rate execution, each execution is planned relative to the planned execution time of the initial execution. If execution is delayed for any reason (such as garbage collection or other background activity), two or more executions will be executed in quick succession to “catch up”.
Docs are here .
Infinite loop
new Thread() { @Override public void run() { while (true) { // Says "blah" every half second System.out.println("blah"); try { Thread.sleep(500); } catch (InterruptedException ie) { // nope } } } }.start();
- Pros : super simple. You can periodically change your recurring delay.
- Cons :
Thread.sleep
still
given the accuracy and accuracy of system timers and schedulers .... and requires catching an InterruptedException
.
Docs are here .
also:
- your infinite loop may require (somehow potentially cumbersome) violation of the condition
- there is no initial delay setting if it is not applied manually until an infinite loop, which will require another
try
/ catch
.
Performers
ScheduledExecutorService es = Executors.newSingleThreadScheduledExecutor(); es.scheduleAtFixedRate( new Runnable() { @Override public void run() {
- Pros : This is the latest feature 3. Very simple and elegant - you can also schedule
Callable
(but not at a fixed speed) and reuse ExecutorService
. The documentation for java.util.Timer
actually mentions ScheduledThreadPoolExecutor
(an implementation of the ScheduledExecutorService
interface) as a "more universal replacement for the Timer
/ TimerTask
combination." - Against as described:
If any execution of this task takes longer than its period, subsequent quotation marks may begin late,
Docs are here .
source share