Reputation: 289
Every 3 seconds, I want the server to send a message. To do this, I have this code.
try {
Thread.sleep(3500);
getPackets().sendGameMessage("[Server Message]: Remember to vote!");
} catch (InterruptedException e) {
e.printStackTrace();
}
The code works of course, waits 3 and a half seconds, sends the message. But how can I make it loop, so every 3 and a half seconds, it will send it without stopping?
Upvotes: 3
Views: 1237
Reputation: 62439
This kind of code is not very useful because it blocks the current thread and also seems to unnecessarily clutter the program logic. It's better to delegate it to a worker thread that executes the send in the background. Also Thread.sleep
is known to be inaccurate.
As of the latest Java versions, I think the most elegant way to do it is using ScheduledThreadPoolExecutor
:
ScheduledThreadPoolExecutor executor = new ScheduledThraedPoolExecutor(1);
executor.scheduleWithFixedDelay(new Runnable() {
public void run() {
getPackets().sendGameMessage("[Server Message]: Remember to vote!");
}
}, 0, 3500, TimeUnit.MILLISECONDS);
Also you don't have to worry about that annoying InterruptedException
.
Upvotes: 0
Reputation: 81074
I'm a bit surprised that someone tackling networking in Java doesn't know how to put code in an infinite loop. Thus, I wonder if your real question is "is there a better way?"
To that question, I would say that you should consider using either java.util.Timer
to send the message, or using scheduleAtFixedRate()
from a ScheduledExecutorService
obtained from Executors.newScheduledThreadPool()
.
Upvotes: 3
Reputation: 5686
spawn the above code in a separate thread and enclose it within a while(true) loop.
Upvotes: 0