Reputation:
I'm trying to have some code to be executed only 2 times with a delay of 500 microseconds between each execution.
So far I have used the ScheduledExecutorService
and an int counter
to track how may times the ExecutorService
has run my code, but I want know if this is a good approach and if there is better way:
private void dingdong() {
ScheduledExecutorService exec = Executors.newSingleThreadScheduledExecutor();
exec.scheduleAtFixedRate(new Runnable() {
int count;
@Override
public void run() {
count++;
//TODO operation
if (count == 2) {
exec.shutdownNow();
}
}
}, 0, 500, TimeUnit.MICROSECONDS);
}
Upvotes: 0
Views: 75
Reputation: 32104
I think the ExecutorService
is overkill. If you just use a normal Thread, it can run your operation, sleep, and run it again.
new Thread(() -> {
doTheThing();
TimeUnit.MICROSECONDS.sleep(500);
doTheThing();
}).start();
Upvotes: 1