Alex DaSilva
Alex DaSilva

Reputation: 289

How could I make a thread loop?

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

Answers (4)

Tudor
Tudor

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

Mark Peters
Mark Peters

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

Mikhail
Mikhail

Reputation: 8028

The best way is to use a Timer. See Java how to write a timer

Upvotes: 0

prathmesh.kallurkar
prathmesh.kallurkar

Reputation: 5686

spawn the above code in a separate thread and enclose it within a while(true) loop.

Upvotes: 0

Related Questions